How to structure packages
__peter__ at web.de
Wed Sep 7 13:30:34 EDT 2011
> I'm learning python, and was playing with structuring packages.
If you are coming from Jave you have to unlearn a thing or two.
> Basically I want to have a package called mypackage that defines a
> number of classes and functions.
> I'm trying to follow the rule that every file defines only one class.
> I could define MyClass in __init__.py, but then what if I wanted to
> define more classes in the mypackage package? My one class per file
> rule goes out the window.
> Is this rule wrongheaded,
> or is there another way to do this?
I recommend that you always start out with a module. Once that becomes
unwieldy you can convert it into a package. Let's assume that
contains a MyClass that you want to move into a separate file. You get the
descriptivename.py # MyClass here
Note that all filenames are lowercase. If you add the line
from .descriptivename import MyClass
to __init__.py you can continue to import and use MyClass with the statement
from mystuff import MyClass
m = MyClass()
m = mystuff.MyClass()
The disadvantage is of course that mystuff.descriptivename will always be
imported, even if you don't need the part of the mystuff package defined
You may also have a look into unittest as an example of a module that was
recently converted into a package. Classes and functions are grouped into
submodules by their functionality rather than employing Java's mechanical
More information about the Python-list