Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class imported from two different paths is not equal?

It seems that entities imported using two different PYTHONPATHs are not the same objects.

I have encouneted a little problem in my code and I want to explain it with a little testcase.

I created the source tree:

a/
  __init__.py
  b/
    __init__.py
    example.py

in example.py:

class Example:
  pass

and from the parent of folder a, I run python and this test:

>>> import sys
>>> sys.path.append("/home/marco/temp/a")
>>> 
>>> import a.b.example as example1
>>> import b.example as example2
>>> 
>>> example1.Example is example2.Example
False

So the question is: why the result is False? Even if imported by two different paths, the class is the same. This is a complete mess if the class is a custom exception and you try to catch it with except.

Tested with python 3.4.3

like image 786
Marco Sulla Avatar asked Dec 06 '16 14:12

Marco Sulla


1 Answers

In Python the class statement is an executable statement, so each time you execute it you will create a new class.

When you import a module Python will check sys.modules to see whether a module at the specified path already exists. If it does then you will just get back the same module, if not it will try to load the module and execute the code it contains.

So two different paths to the same module will load the code twice, which executes the class statement twice and you get two independent classes defined.

This usually hits people when they have a file a.py which they run as a script and then in another module attempt to import a. The script is loaded as __main__ so has different classes and different global variables than the imported module.

The moral is, always be consistent in how you reference a module.

like image 140
Duncan Avatar answered Nov 04 '22 16:11

Duncan