Skip to content
Advertisement

Why do I get False when using issubclass in this way?

Structure:

package/
    m1.py
    m2.py

m1.py:

class A:
    pass


if __name__ == '__main__':
    from m2 import B

    print(issubclass(B, A))

m2.py:

from m1 import A


class B(A):
    pass

I don’t now why I get false while I think it’s obviously true when I run m1.py. My python version is python3.5.2.

Advertisement

Answer

Wellcome to the world of modules and namespaces!

Here is what happens:

In module m2, you import A from module m1. So you create a class m2.A as a reference to class m1.A. It happens to have the same definition as __main__.A, but they are different objects, because the main module is named __main__ and not m1. Then in module __main__ you create a class __main__.B as a reference to class m2.B

To better understand what happens here, I have added some code to m1:

...
print(issubclass(B, A))

import m1
import m2
print(A == m1.A, m1.A == m2.A)
print(B == m2.B)
print(issubclass(B, m2.A), issubclass(B, m1.A))

The output is:

False
False True
True
True True

Proving that B is indeed a subclass of m1.A but not of __main__.A.

Advertisement