Python: Create virtual import path
Is there any way to create a virtual import path in Python?
My directory structure is like this:
- /
- native
- scripts
- some.py
- anoth开发者_如何学编程er.py
- [Other unrelated dirs]
- scripts
- native
The root is the directory from where the program is executed. Atm I add native/scripts/
to the search path so I can do import some, another
instead of from native.scripts import some, another
, but I'd like to be able to do it like this:
from native import some
import native.another
Is there any way to achieve this?
Related questions:
Making a virtual package available via sys.modules
Why not move some.py
and another.py
out into the native
directory so that everything Just Works and so that people returning to the source code later won't be confused about why things are and aren't importable? :)
Update:
Thanks for your comments; they have usefully clarified the problem! In your case, I generally put functions and classes that I might want to import inside, say, native.some
where I can easily get to them. But then I get the script code, and only the script code — only the thin shim that interprets arguments and starts everything running by passing those to a main()
or go()
function as parameters — and put that inside of a scripts
directory. That keeps external-interface code cleanly separate from code that you might want to import, and means you don't have to try to fool Python into having modules several places at once.
In /native/__init__.py
, include:
from scripts import some, another
精彩评论