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, silent=False)
| 121 | |
| 122 | |
| 123 | def import_string(import_name, silent=False): |
| 124 | """Imports an object based on a string. This is useful if you want to |
| 125 | use import paths as endpoints or something similar. An import path can |
| 126 | be specified either in dotted notation (``xml.sax.saxutils.escape``) |
| 127 | or with a colon as object delimiter (``xml.sax.saxutils:escape``). |
| 128 | |
| 129 | If the `silent` is True the return value will be `None` if the import |
| 130 | fails. |
| 131 | |
| 132 | :return: imported object |
| 133 | """ |
| 134 | try: |
| 135 | if ':' in import_name: |
| 136 | module, obj = import_name.split(':', 1) |
| 137 | elif '.' in import_name: |
| 138 | items = import_name.split('.') |
| 139 | module = '.'.join(items[:-1]) |
| 140 | obj = items[-1] |
| 141 | else: |
| 142 | return __import__(import_name) |
| 143 | return getattr(__import__(module, None, None, [obj]), obj) |
| 144 | except (ImportError, AttributeError): |
| 145 | if not silent: |
| 146 | raise |
| 147 | |
| 148 | |
| 149 | def open_if_exists(filename, mode='rb'): |
no test coverage detected
searching dependent graphs…