A pattern for developing python packages.

Home   »   A pattern for developing python packages.

# python_packages #
This document describes a pattern for structuring python packages (mainly CLI tools) 
that will be hosted on GitHub for use by other developers.


## package structure ## 
This would be the structure to organize a package which contains a CLI and several 
other modules or classes which need to be imported.
```
my_tool/
    .gitignore
    README.md
    setup.py

    my_tool/
        MyTool.py
        MyClass.py
        MyModule.py
```
It is important that the package root is the same name as the inner directory which
contains the source code. Also, the main file withe the CLI argument parser should 
be named something different than the package name, to avoid conflicts.


## setup.py ##
The `setup.py` needs a reference to the entrypoint function which runs the argument
parser CLI. See the next section for an example `main()` function which runs the CLI.


## importing classes and modules ##
Importing files should be done as such. They are relative to the root directory of the
package.

```python
from my_tool.MyClass import MyClass


class MyTool:
    def run_cli (self):
        print("Running my command line tool!")


def main ():
    MyTool().run_cli()
```

The main file should contain a function, `main`, or anything as long as it matches that
name within the `setup.py` `entry_points["console_scripts"]` section.

Leave a Reply

Your email address will not be published. Required fields are marked *