
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.suppliesorfrom toolkit.supplies import pack. __init__.pyruns 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 writetoolkit.pack(...).- Inside a package, a relative import like
from .supplies import packmeans "from thesuppliesmodule in this package".
Pip tip: A folder without
__init__.pycan still be imported. It's called a "namespace package". But almost every project uses regular packages with__init__.py.
Assignment
- In the
__init__.pytext, setVERSION = "1.0". - Also in
__init__.py, re-exportpackwith a relative import. - Create
toolkit/signals.pycontainingdef flash(n): return "*" * n. - In the main program,
from toolkit.signals import flashand printflash(3).
- In the
__init__.pytext, setVERSION = "1.0". - Also in
__init__.py, re-exportpackwith a relative import. - Create
toolkit/signals.pycontainingdef flash(n): return "*" * n. - In the main program,
from toolkit.signals import flashand printflash(3).
main.py Python sleeping
Press Run to try your code, then Check to test it.