-
-
Save davedash/2409061 to your computer and use it in GitHub Desktop.
from testing import mocks | |
mocks.email # works | |
# mocks.user doesn't work even though there's a testing/mocks/user.py files | |
import testing.mocks.user # works fine | |
mocks.user # now works: wtf??? | |
rm *.pyc everywhere and mocks/init.py is empty and unmagical.
@kumar303 other items in that directory work, e.g. I can do mocks.email for example.
was mocks.email
imported earlier on in the program maybe? It would be cached in sys.modules
I have the following tree:
├── test.py
└── testing
├── __init__.py
└── mocks
├── __init__.py
├── email.py
└── user.py
I'm only able to import mocks.email and mocks.users if I ask python to import them by name.
from testing import mocks
mocks.email # doesn't work
import testing.mocks.email
mocks.email # works
mocks.user # doesn't work
sys.modules
is just a dict with keys like sys.modules['testing.mocks.email']
-- it's available to all modules everywhere in python. This is useful for many things like shared memory but is not useful for things like isolated dependency trees (the way npm install
does that in node.js). As far as I can tell, you cannot implement isolated dependencies a la node in Python. setuptools tried to do this with crazy hacks but ultimately failed. It was too much magic.
It's just the way python's import system works. Because user.py is a separate file, Python does not import it implicitly. In other words, you didn't ask to import user.py simply by accessing mocks.user. When you access mocks.user, Python looks for a variable named 'user' in the mocks module, it does not try to import anything. You could fix it by adding
from . import user
in yourmocks/__init__.py
if you wanted to