In Python, it's very easy to mess up imports. Something that works right now, may not work anymore when you change something later on. Therefore, it's important to have some sort of structure that always works. On Stack Overflow, I found one way to do this: using the package format. Basically, it looks like this:
.
├── LICENSE
├── MANIFEST.in
├── README.md
├── setup.cfg
├── setup.py
├── test.py
├── yamlradio
│ ├── communicators
│ │ ├── _3fm.py
│ │ ├── _538ib.py
│ │ ├── _538.py
│ │ ├── default.py
│ │ ├── hitfm.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ ├── fabriek.py
│ ├── __init__.py
│ ├── keypress.py
│ ├── parser.py
│ ├── __pycache__
│ ├── radio.py
│ ├── yamlradio.py
│ └── zenders.yml
└── yamlradio-runner.py
In summary:
-
The source should go in a separate directory;
-
The root directory should contain
setup.py
,<name>-runner.py
and miscellaneous files, but no source code; -
__init__.py
in the source directory defines the methods that<name>-runner.py
can access:$ cat yamlradio/__init__.py from .yamlradio import main as rd __all__ = ["rd"]
-
<name>-runner.py
imports themain()
function from the package as defined in__init__.py
, here it isrd
:$ cat yamlradio-runner.py from yamlradio import rd if __name__ == "__main__": rd()
-
setup.py
contains building instructions. Theconsole_scripts
parameter points to themain()
function as defined in__init__.py
:$ cat setup.py #!/usr/bin/env python3 from setuptools import setup, find_packages setup( name = "yamlradio", packages = ["yamlradio"], version = "2.0.1", description = "A small Python3 package to play radio stations as" + \ "defined in a YAML file.", author = "Gijs Timmers", author_email = "[email protected]", url = "https://github.com/GijsTimmers/yamlradio", keywords = ["radio", "terminal", "yaml"], install_requires = ["argparse", "argcomplete", "pyYAML", "cursor"], classifiers = [], entry_points = { 'console_scripts': ['rd=yamlradio:rd']}, include_package_data = True )
- Local imports are prepended with a dot, and they use the `from .<file> import
<Class>` syntax, rather than the `import <file>` syntax.