Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of isinstance function

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 ?

like image 991
Ankur Ankan Avatar asked Dec 14 '14 06:12

Ankur Ankan


1 Answers

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. :)

like image 65
Eevee Avatar answered Oct 05 '22 02:10

Eevee