Skip to content

Instantly share code, notes, and snippets.

@davedash
Created April 17, 2012 21:08
Show Gist options
  • Save davedash/2409061 to your computer and use it in GitHub Desktop.
Save davedash/2409061 to your computer and use it in GitHub Desktop.
wtfpython.py
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???
@kumar303
Copy link

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 your mocks/__init__.py if you wanted to

@davedash
Copy link
Author

rm *.pyc everywhere and mocks/init.py is empty and unmagical.

@davedash
Copy link
Author

@kumar303 other items in that directory work, e.g. I can do mocks.email for example.

@kumar303
Copy link

was mocks.email imported earlier on in the program maybe? It would be cached in sys.modules

@oremj
Copy link

oremj commented Apr 17, 2012

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

@davedash
Copy link
Author

@oremj, @kumar303,

Okay interesting - so it seems like it's a side effect of having had imported it elsewhere in the code.

@kumar303
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment