bpo-29851: Have importlib.reload() raise ImportError if the module's spec is not found by plusminushalf · Pull Request #972 · python/cpython (original) (raw)

Hi @garvitdelhi, for cases like this, it's worth looking through the existing test cases to see if there are some existing examples you can copy, as we tend to have lots of odd helpers in the test suite that let us do things that we expressly tell end users not to do (since we're deliberately inducing error states so we can check for expected exceptions).

For this PR, it turns out the most relevant examples are in tests.test_importlib.test.api: https://github.com/python/cpython/blob/master/Lib/test/test_importlib/test_api.py#L198

As with the examples there, the simplest way to get a module that can't be reloaded is to take a normal module and corrupt its metadata, as in something like:

>>> import types
>>> import importlib
>>> importlib.reload(types)
<module 'types' from '/usr/lib64/python3.5/types.py'>
>>> import sys
>>> types.__name__ = "not_a_module"
>>> types.__spec__ = None
>>> sys.modules[types.__name__] = types
>>> importlib.reload(types)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.5/importlib/__init__.py", line 166, in reload
    _bootstrap._exec(spec, module)
  File "<frozen importlib._bootstrap>", line 607, in _exec
AttributeError: 'NoneType' object has no attribute 'name'