Strange behavior of the isinstance function

I have a class called Factor in the Factor.py module ( https://github.com/pgmpy/pgmpy/blob/dev/pgmpy/factors/Factor.py ), as well as a function called factor_product in Factor.py like:

 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, even if I pass the Factor function to a function, it throws a TypeError . A few lines from the debugger with a breakpoint set 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?

+6
source share
2 answers

reload is a good way to get two copies of the same class from the same module: one of them before rebooting (if all instances of this class are still hidden) and one of them 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 quite true that your objects are not instances of Factor ... and not Factor , anyway.

Never trust reload . :)

+6
source

How isinstance Return true if the object argument is an instance of the classinfo argument or a (direct, indirect or virtual) subclass, it simply returns true if you pass an 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 
0
source

Source: https://habr.com/ru/post/979565/


All Articles