This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: importlib of module results in different id than when imported with import keyword
Type: behavior Stage: resolved
Components: Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: brett.cannon, pdxjohnny
Priority: normal Keywords:

Created on 2020-04-28 19:00 by pdxjohnny, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg367554 - (view) Author: John Andersen (pdxjohnny) * Date: 2020-04-28 19:00
When importing a file using importlib the id() of the object being imported is not the same as when imported using the `import` keyword. I feel like this is a bug. As if I have a package which is using relative imports, and then I import all of the files in that package via importlib. issubclass and isinstance and others no longer work when the relative imported object and then importlib imported object are checked against each other, I assume because the id()s are different.

$ cat > target.py <<'EOF'
class Target:
    pass

EOF

$ cat > importer.py <<'EOF'
import importlib
from target import Target

spec = importlib.util.spec_from_file_location("target", "target.py")
imported_by_importlib = importlib.util.module_from_spec(spec)
spec.loader.exec_module(imported_by_importlib)

print("isinstance(imported_by_importlib.Target(), Target:",
isinstance(imported_by_importlib.Target(), Target))
print("id(Target):", id(Target))
print("id(imported_by_importlib.Target):", id(imported_by_importlib.Target))

EOF

$ python importer.py
isinstance(imported_by_importlib.Target(), Target: False
id(Target): 93824998820112
id(imported_by_importlib.Target): 93824998821056
msg367555 - (view) Author: Brett Cannon (brett.cannon) * (Python committer) Date: 2020-04-28 19:08
That's expected because you are constructing a completely new module object with importlib.util.module_from_spec(). You're also completely circumventing sys.modules with the code you wrote which is the only way you would get equivalent IDs compared to using the import statement.

So this is working as intended.
msg367704 - (view) Author: John Andersen (pdxjohnny) * Date: 2020-04-29 21:42
Thank you! :) I must have missed that somehow
History
Date User Action Args
2022-04-11 14:59:30adminsetgithub: 84607
2020-04-29 21:42:04pdxjohnnysetmessages: + msg367704
2020-04-28 19:08:01brett.cannonsetstatus: open -> closed

nosy: + brett.cannon
messages: + msg367555

resolution: not a bug
stage: resolved
2020-04-28 19:00:54pdxjohnnycreate