Python Scripts and Modules


  • Any Python file can be considered a ‘module’, and can be import-ed. This just runs the code in the file, and makes the names of any objects in the module accessible using dot-notation.
  • If we bundle our Python scripts into a collection of functions, we can reuse those functions in other modules or in the Python interpretter.
  • After turning our scripts into reusable modules, we can maintain script-like behaviour using the idiom if __name__ == "__main__".
  • argparse can be used to create sophisticated command line interfaces.

From Modules to Packages


  • Packages can be used to better organise our code as it becomes more complex
  • Packages are defined by a directory structure and the presence of __init__.py
  • By controlling what is or isn’t imported in __init__.py, we can define a public API for our project.
  • A package can be run as a script using the -m flag, provided it contains a file __main__.py.
  • Through clever use of argparse, we can provide a rich scripting interface to a whole package.

Building and Installing Packages using setuptools


  • We can configure our projects for pip installation by setting up a pyproject.toml file.
  • Simple projects require very little to be added to this file, but there are many optional extras we can add.

Extra: A History of Python Build Tools


  • The ‘best practices’ for Python packaging has changed a number of times, and there are now many competing tools for accomplishing the same task.
  • Be wary of information on this topic in online tutorials – not all guides have been updated to use the most recent methods, and some advice may no longer be relevant.

Publishing our Python Packages


  • Versioning our projects is important so that our users know what’s compatible.
  • GitHub is a powerful service for hosting our projects and managing their development.
  • Each new release of our packages should be uploaded to PyPI using build and twine.