weird isinstance/issubclass behavior?

Chris Angelico rosuav at gmail.com
Thu Nov 29 10:08:20 EST 2012


On Fri, Nov 30, 2012 at 1:59 AM, lars van gemerden <lars at rational-it.com> wrote:
> Basically if i import a class as:
>
>     from mod1.mod2 import A
>
> or:
>
>     from mod0.mod1.mod2 import A
>
> which both result in importing the same class, a call to isinstance(inst, A) in another module can have a different output.

What you may be seeing there is that you've imported the module twice.
There are two entirely separate module objects, taken from the same
file. Something instantiated from one class isn't an instance of the
other class even if they're indistinguishable classes; a little
monkeypatching might show you what's going on (fiddle with one class,
check the other, fiddle hasn't happened).

As a general rule, importing a module in different ways is considered
dangerous. Be consistent, and then this sort of oddity won't occur -
and you also won't have other oddities, eg with other global state.

ChrisA



More information about the Python-list mailing list