There is a strange behavior of isinstance if used in __main__
space.
Consider the following code
a.py:
class A(object):
pass
if __name__ == "__main__":
from b import B
b = B()
print(isinstance(b, A))
b.py
from a import A
class B(A):
pass
main.py
from a import A
from b import B
b = B()
print(isinstance(b, A))
When I run main.py
, I get True
, as expected, but when I run a.py
, I am getting False
. It looks like the name of A
is getting the prefix __main__
there.
How can I get a consistent behavior?
I need this trick with import of B
in a.py
to run doctest
on file a.py
.
Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
In Python, the built-in functions type() and isinstance() help you determine the type of an object. type(object) – Returns a string representation of the object's type. isinstance(object, class) – Returns a Boolean True if the object is an instance of the class, and False otherwise.
type() returns the type of the object you put in as an argument, and is usually not useful unless compared with a real type (such as type(9) == int ). isinstance() returns a boolean - true or false - based on whether the object is of given type.
WSo what happens when you run a.py
is that Python reads a.py
and executes it. While doing so, it imports module b
, which imports module a
, but it does not reuse the definitions from parsing it earlier. So now you have two copies of the definitions inside a.py
, known as modules __main__
and a
and thus different __main__.A
and a.A
.
In general you should avoid importing modules that you are executing as well. Rather you can create a new file for running doctests and use something like
import a
import doctest
doctest.testmod(a)
and remove the __main__
part from module a
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With