Context manager to manage the various importers and stored state in the sys module. The 'modules' attribute is not supported as the interpreter state stores a pointer to the dict that the interpreter uses internally; reassigning to sys.modules does not have the desired effect.
(**kwargs)
| 192 | |
| 193 | @contextlib.contextmanager |
| 194 | def import_state(**kwargs): |
| 195 | """Context manager to manage the various importers and stored state in the |
| 196 | sys module. |
| 197 | |
| 198 | The 'modules' attribute is not supported as the interpreter state stores a |
| 199 | pointer to the dict that the interpreter uses internally; |
| 200 | reassigning to sys.modules does not have the desired effect. |
| 201 | |
| 202 | """ |
| 203 | originals = {} |
| 204 | try: |
| 205 | for attr, default in (('meta_path', []), ('path', []), |
| 206 | ('path_hooks', []), |
| 207 | ('path_importer_cache', {})): |
| 208 | originals[attr] = getattr(sys, attr) |
| 209 | if attr in kwargs: |
| 210 | new_value = kwargs[attr] |
| 211 | del kwargs[attr] |
| 212 | else: |
| 213 | new_value = default |
| 214 | setattr(sys, attr, new_value) |
| 215 | if len(kwargs): |
| 216 | raise ValueError('unrecognized arguments: {}'.format(kwargs)) |
| 217 | yield |
| 218 | finally: |
| 219 | for attr, value in originals.items(): |
| 220 | setattr(sys, attr, value) |
| 221 | |
| 222 | |
| 223 | class _ImporterMock: |
no test coverage detected
searching dependent graphs…