开发者

Python: Create virtual import path

开发者 https://www.devze.com 2023-04-04 21:56 出处:网络
Is there any way to create a virtual import path in Python? My directory structure is like this: / native

Is there any way to create a virtual import path in Python?

My directory structure is like this:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消