[issue44922] isinstance breaks on imported dataclasses

Eric V. Smith report at bugs.python.org
Mon Aug 16 02:05:16 EDT 2021


Eric V. Smith <eric at trueblade.com> added the comment:

You're importing main.py twice. The first is when you run "python main.py", where it has the module name '__main__'. The second time is in codegen.py, where it has the name 'main'. You create the AtomX instance as __main__.AtomX, but the isinstance check is against main.AtomX. Because the objects have different modules, they're not equal.

You can see this if you change the isinstance check to:

=============
from main import AtomX
import sys

def inheritance_map(candidate):
    assert isinstance(candidate, sys.modules['__main__'].AtomX)
==============

Another way to see this if you add a print statement to the original codegen.py:

==============
from main import AtomX

def inheritance_map(candidate):
    print(f'{candidate=} {type(candidate)=} {AtomX=}')
    assert isinstance(candidate, AtomX)
==============

Which will print:
candidate=AtomX(my_symbol='qwerty', quantity='') type(candidate)=<class '__main__.AtomX'> AtomX=<class 'main.AtomX'>
Notice the types refer to different modules, so they are distinct and unequal.

The easiest way around this is to not do any work in main.py, but instead create another module, import it from main.py, and do the work there.

----------
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44922>
_______________________________________


More information about the Python-bugs-list mailing list