Lay out import pathing in Python, straight and sim

2019-02-19 14:45发布

问题:

If a group of Python developers wants to put their shared code somewhere, in a hierarchical structure, what's the structure, and what's the related "import" syntax?

Does java-style reference work in Python also? I.e., do directories correspond to dots?

What is standard setup for an internal-use-only library of Python code, and what's the syntax for imports from that library area, say 3 levels deep?

I've read Learning Python, saw PYTHONPATH, been fiddling with code for a few weeks now, love it, but I'm just dense on "import" beyond trivial cases. If too general send me back to the books.

回答1:

If a group of Python developers wants to put their shared code somewhere, in a hierarchical structure, what's the structure, and what's the related "import" syntax?

You put it in your C:\python26\Lib\site-packages\ directory under your own folder.

Inside that folder you should include an __init__.py file which will be run upon import, this can be empty.

Does java-style reference work in Python also? I.e., do directories correspond to dots?

Yes as long as the directories contain __init__.py files.

What is standard setup for an internal-use-only library of Python code, and what's the syntax for imports from that library area, say 3 levels deep?

MyCompany/MyProject/ -> import MyCompany.MyProject


回答2:

What we do.

Development

  • c:\someroot\project\thing__init__.py # makes thing a package

  • c:\someroot\project\thing\foo.py

  • c:\someroot\project\thing\bar.py

Our "environment" (set in a variety of ways

SET PYTHONPATH="C:\someroot\project"

Some file we're working on

 import thing.foo
 import thing.bar

Deployment

  • /opt/someroot/project/project-1.1/thing/init.py # makes thing a package

  • /opt/someroot/project/project-1.1/thing/foo.py

  • /opt/someroot/project/project-1.1/thing/bar.py

Our "environment" (set in a variety of ways

SET PYTHONPATH="/opt/someroot/project/project-1.1"

This allows multiple versions to be deployed side-by-side.

Each of the various "things" are designed to be separate, reusable packages.



标签: python import