Best practises for imports in Python 3 packages and scripts

前端 未结 1 626
面向向阳花
面向向阳花 2021-01-20 13:23

Consider this simple folder structure:

root
  Package1
    x.py
    y.py
  Package2
    z.py
  Examples
    main.py

Now our requirements a

相关标签:
1条回答
  • 2021-01-20 14:03

    As always, there are two separate steps:

    1. You write the code against the abstract namespace of packages, which contains package1 and package2 (and sys, os, etc.), but not “Examples” which is not a package (because main.py is not a module).
    2. You set sys.path appropriately before any of your code ever runs. If it's your own (uninstalled) code, there are places you can put it, or you can write an easy shell script wrapper to set PYTHONPATH for your python process.

    So the answers to your questions are

    1. In x.py you write from . import y. (Python 2 supports this and 3 requires it.)
    2. How you set sys.path depends on your packaging/environment system. The traditional way is to set the PYTHONPATH environment variable for the python process, but there are other ways involving things like the site module.
    3. from package1 import y is the usual way to name things only once.
    0 讨论(0)
提交回复
热议问题