Starting a new Python Package
- This post shows you good baseline layouts for different projects like CLI applications, standalone scripts, or packages.
This post summarizes the sources I regularly refer to when starting a new Python package. I’ve done this a few times and had to find the relevant articles again each time, so I’m collecting all the information here for my next project.
Use an IDE
I’ve used Emacs Python-mode (
elpy) for far too long. Use PyCharm, it’s way
Use one. Here is how to do it in PyCharm.
pip freeze > requirements.txt.
- Kenneth Reitz’s post and the corresponding repository
- This site gives you an overview of how a package folder should look.
- A good step-by-step guide to transform your code into a package is available here
- The main packaging site has more information
- Also nice:
If you followed the file structure in the Hitchhiker’s guide linked above, you
should have a
docs folder. I’ve used
to write the documentation for previous projects and really like it.
sphinx-quickstart in your
docs/ folder to quickly set up the initial
conf.py must be edited in the following points:
- To automatically set the version, set the
version = __import__('pfc').__version__
extensionslist to be able to use NumPy style docstrings
- If you want to include Jupyter Notebooks in your documentation (as “vignettes”
or quickstart tutorials), add
- The top section “Path setup” is commented out. Uncomment the three lines and
make the third one
sys.path.insert(0, os.path.abspath('..'))to include your package’s root directory and make imports and autodoc work.
Sphinx can automatically create documentation based on your classes’ docstrings. Google for “sphinx autodoc automodule” to find out more.
My last project has
modules.rst in the docs that just lists all modules’ classes; it looks
Modules ======= Config ------ .. automodule:: sng.Config :members: Generator --------- .. automodule:: sng.Generator :members: Wordlists --------- .. automodule:: sng.wordlists.wordlists :members:
These modules’ documentation gets autogenerated from the docstrings.
In my projects, Sphinx seems to automatically recognize Google style docstrings
and NumPy style docstrings (official definition here). But there is an extension called
that does that, too. It might be useful to add that to the
extensions list in some cases, but I don’t know.
I have used NumPy style docstrings before. An example from here looks like this:
But it’s better to document the constructor arguments in the
__init__ method instead of directly under the class, see here.