Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If the
(import_name: str, silent: bool = False)
| 129 | |
| 130 | |
| 131 | def import_string(import_name: str, silent: bool = False) -> t.Any: |
| 132 | """Imports an object based on a string. This is useful if you want to |
| 133 | use import paths as endpoints or something similar. An import path can |
| 134 | be specified either in dotted notation (``xml.sax.saxutils.escape``) |
| 135 | or with a colon as object delimiter (``xml.sax.saxutils:escape``). |
| 136 | |
| 137 | If the `silent` is True the return value will be `None` if the import |
| 138 | fails. |
| 139 | |
| 140 | :return: imported object |
| 141 | """ |
| 142 | try: |
| 143 | if ":" in import_name: |
| 144 | module, obj = import_name.split(":", 1) |
| 145 | elif "." in import_name: |
| 146 | module, _, obj = import_name.rpartition(".") |
| 147 | else: |
| 148 | return __import__(import_name) |
| 149 | return getattr(__import__(module, None, None, [obj]), obj) |
| 150 | except (ImportError, AttributeError): |
| 151 | if not silent: |
| 152 | raise |
| 153 | |
| 154 | |
| 155 | def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]: |
no test coverage detected