Cheat Sheet about Python

This site is a reply to

.

Publishing to PyPI

In order to publish a python package on
PyPI, follow these steps:

  1. Create an account on PyPI.
  2. Create an account on PyPI test.
  3. Write a setup.py. (Example will follow below)
  4. Execute python setup.py dist. (This need some more detail, e.g. sdist,
    wheel and so on should be explained)
  5. Run twine upload --repository-url https://test.pypi.org/legacy/ dist/*
    and check the results on PyPI test.
  6. If fine, execute twine upload dist/*.

Congratulations! You published a package on PyPI!

Default logging configuration

Python comes with a logging module.
In order to have a consitent format across all modules, you can define the
following in your top-most __init__.py:

import logging
import sys

logging.baseConfig(
  level=logging.DEBUG,
  format="%(asctime)s (%(levelname)s) %(module)s - %(funcName)s: %(message)s",
  datefmt="%Y-%m-%d %H:%%M:%S",
  stream=sys.stdout
)

Then, from anywhere, use the logger like so:

import logging

logger = logging.getLogger(__file__)


def my_func():
    logger.debug("Hello {}".format("World"))

Setting up Sphinx

It took me quite some time, but I finally figured out a working process to
setup sphinx!

Kudos to Sam Nicholls.

mkdir docs
cd docs
sphinx-quickstart  # Most defaults can be accepted
vim conf.py  # See below
sphinx-apidoc -o source/ ../<package>
vim index.rst  # See below
make html

conf.py

Installing ReadTheDocs theme

pip install sphinx_rtd_theme

Then, around line 52, change the theme from alabaster to

html_theme = 'sphinx_rtd_theme'

Enabling extensions

Around line 33 update the lines so they look like the following:

extensions = [
  'sphinx.ext.autodoc',
  'sphinx.ext.viewcode'
]

Don't forget to uncomment those lines (around line 13):

import os
import sys
sys.path.insert(0, os.path.abspath('../'))

index.rst

Update the file so that it looks like this (<package> refers to your code):

Welcome to <package>'s documentation!
=====================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   readme
   source/modules


Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

readme.rst

This allows you to keep your README.rst at the root of the repo, while also
include it in the documentation:

.. include:: ../README.rst