how to arrange classes in .py files?

Michael Torrie torriem at gmail.com
Fri Mar 27 21:52:41 CET 2009


Kent wrote:
> In java, usually a .java file contains One Class. I read some python
> codes, I found one py file can have many classes and functions. Is
> there any convention how to manage python classes into .py files?

In python we have a real name space, the primary unit being the
"module."  Think of a module as a singleton really, with any code in
module being executed upon import (a sort of constructor).  Python
classes are really just objects, so you can put as many related objects
in a module as you want, or is appropriate (more on this later), and
refer to them with the "module.object" notation.  If you need to spread
your code that's in one namespace out over several files for clarity and
ease of debugging, you can create a python "package[1]" which consists
of an __init__.py that can pull in various names from other files in the
package into the namespace it is defining.  A python package is imported
as if it was a normal module.

How you are organizing your python code is probably fine, but wouldn't
be considered very pythonic and familiar to many python programmers.
Most of us don't want to have to deal with something like:

import mymodule

myobject=mymodule.class.Class()

as that is redundant.  Rather, myobject=mymodule.Class() is expected.
Sounds to me like your style of programming may lend itself to using a
python package as an organizational unit for your code.

Typically my modules have the following structure:
- set up any module variables and constants
- exception classes
- internal functions or classes (private to the module)
- public functions or classes
- module-level code to perform any on-load stuff
- an if __name__=="__main__" section for doing unit testing

My modules are typically defined according to function.  Common module
names would include config, utilities, etc.

Since the singleton is the pattern that I use the most, I actually
rarely need classes at all in most modules, except to define exceptions
my module will raise.  I consider functions in modules to be the
equivalent of methods on a static class.  Quite a refreshing break from
the way Java forces me to work.  And much cleaner too.

Often as I develop a module, I'll factor out code that's generic out of
the module into its own module.  There should be very loose coupling
between modules, and very tight coupling within the module, though not
necessarily... a collection of utility functions are often just
collected in a module for convenience.  Coupling is a good indicator of
whether you should factor the code out into its own module.  Finally, if
I want to take a group of modules and export a simple, clean, public
interface, I'll wrap the modules in a package.

[1] http://docs.python.org/tutorial/modules.html#packages



More information about the Python-list mailing list