I’ve avoided putting my Python modules into packages. That’s because (like a lot of other folks) I don’t really understand how to create a package. And that’s because (probably like a lot of other folks) I’m too time-constrained and over-worked to be able to grok anything except a very short, clear, and simple explanation of how packages work… and I never found one.
That’s all over now. In a post on comp.lang.python Steven D’Aprano has made it all beautifully clear. Here is an excerpt from his post. This is the part that really turned on the lights for me.
A package is a special arrangement of folder + modules.
To be a package, there must be a file called __init__.py in the folder, e.g.:
parrot/ +-- __init__.py +-- feeding/ +-- __init__.py +-- eating.py +-- drinking.py +-- fighting.py +-- flying.py +-- sleeping.py +-- talking.py
This defines a package called parrot which includes a sub-package feeding and modules fighting, flying, sleeping and talking. You can use it by any variant of the following:
import parrot # loads parrot/__init__.py import parrot.talking # loads parrot/talking.py from parrot import sleeping import parrot.feeding from parrot.feeding.eating import eat_cracker #... and so on ...
Common (but not compulsory) behaviour is for parrot/__init__.py to import all the modules in the package, so that the caller can do this:
import parrot parrot.feeding.give_cracker()
without needing to manually import sub-packages. The os module behaves similarly: having imported os, you can immediately use functions in os.path without an additional import.
Just dumping a bunch of modules into a folder doesn’t make it a package, it just makes it a bunch of modules in a folder. Unless that folder is in the PYTHONPATH, you won’t be able to import the modules because Python doesn’t look inside folders. The one exception is that it will look inside a folder for a __init__.py file, and if it finds one, it will treat that folder and its contents as a package.
- Put your modules in a package,
- tell the user to just place the entire package directory where they normally install Python code (usually site-packages — Steve Ferg), and
- importing will just work
Thank you, Steven! You have no idea how much we needed that!
Updated 2011-11-06 to improve formatting