Code

Packing the Toolkit

When you have many modules, group them in a package: a folder with an __init__.py file.

toolkit/
    __init__.py      # runs on `import toolkit`
    supplies.py      # toolkit.supplies
    signals.py       # toolkit.signals
  • Import submodules with dots: import toolkit.supplies or from toolkit.supplies import pack.
  • __init__.py runs when the package is first imported. It can be empty, or it can define shared values and re-export handy names so users can simply write toolkit.pack(...).
  • Inside a package, a relative import like from .supplies import pack means "from the supplies module in this package".

Pip tip: A folder without __init__.py can still be imported. It's called a "namespace package". But almost every project uses regular packages with __init__.py.

Assignment

  1. In the __init__.py text, set VERSION = "1.0".
  2. Also in __init__.py, re-export pack with a relative import.
  3. Create toolkit/signals.py containing def flash(n): return "*" * n.
  4. In the main program, from toolkit.signals import flash and print flash(3).