Starting a new Python Package
Further Reading
- https://samnicholls.net/2016/06/15/how-to-sphinx-readthedocs/
- This post shows you good baseline layouts for different projects like CLI applications, standalone scripts, or packages.
Introduction
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
easier.
Virtual Environment
Use one. Here is how to do it in PyCharm.
Remember to pip freeze > requirements.txt
.
Sources
- 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:
- https://realpython.com/python-continuous-integration/#packaging
- https://www.pypa.io/en/latest/
Documentation
If you followed the file structure in the Hitchhiker’s guide linked above, you
should have a docs
folder. I’ve used
Sphinx
(project homepage)
to write the documentation for previous projects and really like it.
Run sphinx-quickstart
in your docs/
folder to quickly set up the initial
files.
The conf.py
must be edited in the following points:
- To automatically set the version, set the
version
variable toversion = __import__('pfc').__version__
- Add
"numpydoc"
to theextensions
list to be able to use NumPy style docstrings - If you want to include Jupyter Notebooks in your documentation (as “vignettes”
or quickstart tutorials), add
"nbsphinx"
to theextensions
list. - 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.
Docstrings
Sphinx can automatically create documentation based on your classes’ docstrings. Google for “sphinx autodoc automodule” to find out more.
My last project has
a file modules.rst
in the docs that just lists all modules’ classes; it looks
like this:
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.
Docstring style
In my projects, Sphinx seems to automatically recognize Google style docstrings
and NumPy style docstrings (official definition here). But there is an extension called
Napoleon
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.