I define a dataclass MyClass
in module A
and create two instances of it, a
in module A
and b
in module B
.
When comparing the two, it always returns False
, since a
has type <class '__main__.MyClass'>
and b
has type <class 'A.MyClass'>
.
Is this expected behaviour (python version is 3.13.2)?
If yes, what would be a good way to compare two instances of the same dataclass when one is not sure type
returns the same for both instances?
If no, should this be fixed in dataclasses
or is this a python issue?
MWE without the dataclasses, just a raw class:
module A:
import B
class MyClass:
pass
if __name__ == '__main__':
a=MyClass()
b=B.b()
print(type(a))
print(type(b))
module B:
import A
def b():
return A.MyClass()
When running A.py
, the output is
<class '__main__.MyClass'>
<class 'A.MyClass'>
This is an interesting point. The problem here is that the A.py
is not the module A
but the module __main__
.
First change A.py
to give it a main
function:
import B
class MyClass:
pass
def main():
a=MyClass()
b=B.b()
print(type(a))
print(type(b))
if __name__ == '__main__':
main()
Almost the same isn't it?
The difference is that you can now first import it as a module and then call its main
function:
python -c "import A; A.main()"
Which gives as expected
<class 'A.MyClass'>
<class 'A.MyClass'>