Skip to content

Instantly share code, notes, and snippets.

@GijsTimmers
Created December 14, 2015 16:35
Show Gist options
  • Save GijsTimmers/1788da520a05655b6c71 to your computer and use it in GitHub Desktop.
Save GijsTimmers/1788da520a05655b6c71 to your computer and use it in GitHub Desktop.
On importing packages in Python

On importing

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 the main() function from the package as defined in __init__.py, here it is rd:

    $ cat yamlradio-runner.py
    from yamlradio import rd
    
    if __name__ == "__main__":
        rd()
    
  • setup.py contains building instructions. The console_scripts parameter points to the main() 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment