Isinstance() not working as expected when passing objects as arguments to functions (Inheretance)

When working on a project I stumbled upon a problem with isinstance(). I have made a simple example to ilustrate it:

test.py

import testAux

class Developer(object):
    # Constructor
    def __init__(self, name):
        self.name = name

class PythonDeveloper(Developer):
    # Constructor
    def __init__(self, name, language):
        self.name = name
        self.language = language

# Object of PythonDeveloper
dev = PythonDeveloper("Eric", "Python")

if __name__=="__main__":
    # is python_dev object an instance of a Developer Class
    print(isinstance(dev, Developer))
    # Output True

    testAux.PassMeObject(dev)

testAux.py

from test import *

class PassMeObject():
    def __init__(self, obj: PythonDeveloper) -> None:
        print(isinstance(obj, Developer))
        pass

Basically I instance PythonDeveloper an store it in dev and then pass this obj to PassMeObject.
I print isinstance(obj, Developer) from both places on the same variable. But the outputs are diferent:

True
False

How is this possible? How can I fix it?

I think, it is a kind of "__main__ vs. module_name" discrepancy -I hope I am using the right word-.
I have tried to modify your code:

test.py

[...]
if __name__=="__main__":
    # is dev object an instance of a PythonDeveloper Class
    print(isinstance(dev, PythonDeveloper))
    print(dev.__class__, PythonDeveloper)

    testAux.PassMeObject(dev)

testAux.py

from test import *
class PassMeObject():
    def __init__(self, obj: PythonDeveloper) -> None:
        print(isinstance(obj, PythonDeveloper))
        print(obj.__class__, PythonDeveloper)

Output will probably help you at finding the source of the error:

True
<class '__main__.PythonDeveloper'> <class '__main__.PythonDeveloper'>
False
<class '__main__.PythonDeveloper'> <class 'test.PythonDeveloper'>

(I have tried to simplify your code : it is not isinstance-checking for the parent class but for the child one)

3 Likes

That was indeed the problem.

To solve it I just created a new file an put the contents of
if __name__=="__main__":
inside that file.

Thank you very much :slight_smile:

1 Like