简体   繁体   中英

Python Intra-Package Imports - How do I get common functions/classes spread throughout my package?

I have a set of python scripts organized like so:

PythonScripts/
     TypeAScripts/
        TypeASet1Scripts/
            example.py
        TypeASet2Scripts/
     TypeBScripts/
        TypeBSet1Scripts/
        TypeBSet2Scripts/
     TypeCScripts/
        TypeCSet1Scripts/
        TypeCSet2Scripts/
     CommonFunctions/
        CommonFunctions.py

with init.py in every folder. What I want is to be able to run example.py where example.py imports from CommonFunctions . I want scripts throughout folders A,B, and C to do the same.

To do this with absolute imports, you'd put

 import PythonScripts.CommonFunctions.CommonFunctions 

However, this only works if PythonScripts is in your python path. Which, if you are just running example.py in that folder, isn't going to be the case. You can add it with sys.append() , but this seems like an awkward way of doing it. Is there any better approach?

Python supports relative imports, but in my experience they're finicky and don't do what you would expect them to do. You can find more information about them in PEP 328 .

I would suggest properly packaging your modules and writing a setup.py file to install them into the global site-packages directory. This will allow you to reference your modules from anywhere on the system using absolute imports and additionally provides you the option of registering them with the Python Package Index (PyPi) for distribution to third parties. A good tutorial on how to do this is "The Hitchhiker's Guide to Packaging 1.0" .

Additionally, if you're concerned about borking your global site-packages directory I'd suggest you do your test installs in a Python virtual environment . The virtualenv tool in particular makes working with virtual environments simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM