Can anyone explain this weird Python / Django import behavior?

I have a project in which the directory structure is as follows:

mywebsite/ manage.py __init__.py myapp/ models/ __init__.py base.py 

myapp / models / base.py contains:

 class X(object): pass 

myapp / models / __ init__.py contains:

 from base import X 

Now, if I use the manage.py shell, I may have the following session:

 > import mywebsite.myapp.models > import myapp.models > mywebsite.myapp.models.X == myapp.models.X False 

However, if I modify myapp / models / __ init__.py to be:

 from myapp.models.base import X 

Then I get True as expected.

I think I'm missing something about how imports work or how Django changes paths when using the manage.py shell.

Can anyone explain this?

+4
source share
1 answer

When you open the Django shell, it adds the path to your project in sys.path . You can see this by running import sys; print sys.path import sys; print sys.path in the Django shell and in the regular python shell and comparing the output. You will notice that the output of the Django shell includes the path to the mywebsite directory as the first element of the list.

This basically means that two imports create two different module objects, since they are obtained from different points in the search path . Comparison check returns False, since module objects have different identifiers (memory address)

 # These two values will be different id(mywebsite.myapp.models) id(myapp.models) 
+4
source

All Articles