Skip to content Skip to sidebar Skip to footer

Python: Isinstance() Undefined Global Name

I'm new with Python and I'm trying to use classes to program using objects as I do with C++. I wrote 3 .py files. a.py from b import * class A: def __init__(self): sel

Solution 1:

As pointed in some comment, circular dependencies are not well handled if imported in the form from a import A.

In short, the problem with ... import * is that is causes the local scope to have all its declarations overridden, in effect making the identification of from which module (in your case) a class comes from. This causes exactly what you are facing.

Changing the import statement in the following way, together with a classified reference to a.A, produces OK as output.

import a

class B:
    def __init__(self):
        self.m_tName = "B"

    def do(self, tA ):
        print tA
        if not isinstance( tA, a.A ):
            print ( "invalid parameter" )

        print( "OK" )

As a bit of additional information, this has already been discussed in Why is "import *" bad?. I would point in special to this answer: https://stackoverflow.com/a/2454460/1540197.

**Edit:**This article explain the import confusion.


Solution 2:

You have a circular dependancy, a.py and b.py import each other.

You could move either import statement inside the method where it is used. So b.py would become:

class A:
    def __init__(self):
        self.m_tName = "A"

    def test(self):
        from b import B
        tB = B()

        tB.do( self )

Post a Comment for "Python: Isinstance() Undefined Global Name"