Strange behaviour of isinstance function

534 Views Asked by At

I have a class named Factor in the module Factor.py (https://github.com/pgmpy/pgmpy/blob/dev/pgmpy/factors/Factor.py) and also have function named factor_product in Factor.py as:

def factor_product(*args):
    if not all(isinstance(phi, Factor) for phi in args):
            raise TypeError("Input parameters must be factors")
    return functools.reduce(lambda phi1, phi2: _bivar_factor_operation(phi1, phi2,     
                                                            operation='M'), args)

Now if I even pass instances of Factor to the function, it still throws TypeError. A few lines from the debugger with breakpoint set just above the if statement:

(Pdb) args
args = (<pgmpy.factors.Factor.Factor object at 0x7fed0faf76a0>, <pgmpy.factors.Factor.Factor object at 0x7fed0faf7da0>)

(Pdb) isinstance(args[0], Factor)
False

(Pdb) type(args[0])
<class 'pgmpy.factors.Factor.Factor'>

(Pdb) Factor
<class 'pgmpy.factors.Factor.Factor'>

Any idea why this is happening ?

2

There are 2 best solutions below

0
On BEST ANSWER

reload is a good way to end up with two copies of the same class from the same module: one from before the reload (if any instances of that class are still lurking about) and one from after.

Most likely you had objects of the new type, but Factor referred to the old type, since it was imported some time ago. So it's completely true that your objects aren't instances of Factor... not that Factor, anyway.

Never trust reload. :)

1
On

As isinstance Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof , it just return true if you pass the instance of your class to it not the class itself , see the following example :

>>> class A :
...  pass
... 
>>> isinstance(A,A)
False
>>> isinstance(A(),A)
True
>>> z=A()
>>> isinstance(z,A)
True