Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling isinstance in main Python module

Tags:

python

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.

like image 722
Dmitry K. Avatar asked Mar 11 '14 10:03

Dmitry K.


People also ask

What does Isinstance in Python mean?

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.

How do you check if an object belongs to a certain class in Python?

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.

What is the difference between the type () and Isinstance () in Python?

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.


1 Answers

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.

like image 118
Helmut Grohne Avatar answered Oct 23 '22 02:10

Helmut Grohne