How to structure packages
Peter Otten
__peter__ at web.de
Wed Sep 7 13:30:34 EDT 2011
bclark76 wrote:
> 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,
Yes.
> 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
mystuff.py
contains a MyClass that you want to move into a separate file. You get the
following files:
mystuff
__init__.py
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()
or
import mystuff
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
there.
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
one-class-per-file pattern.
More information about the Python-list
mailing list