how to arrange classes in .py files?
David L. Jones
david.l.jones at gmail.com
Fri Mar 27 15:01:57 CET 2009
On Mar 26, 8:51 pm, Kent <kent.y... at gmail.com> wrote:
> ... Is
> there any convention how to manage python classes into .py files?
> In above packages, each .py file contains one python class. And
> ClassName = Filename
> Can anyone give some hint on it? would be great with reason.
Overall, I don't think there is a single convention that anyone can
point to and everyone will at least acknowledge as convention.
If you have multiple single-class files, then you will have
unnecessary redundancy referencing the classes from outside:
# Module structure: mymodule/
c = mymodule.someclass.someclass()
You can get around this with a Java-like statement:
# Same module structure
from mymodule.someclass import someclass # or from ... import *
c = someclass()
but you lose namespacing which can make code more difficult to read. I
think that this Java-style approach of pulling everything into the
current namespace is quite silly, since Python's module structure was
specifically designed in large part not to work like this. (Commence
I tend to think in terms of coupling and cohesion. Within an
application, any classes, functions, data, etc. that are tightly
coupled are candidates to live in the same file. If you have a set of
classes that all inherit from a common set of base classes, then you
should probably consider putting the base and inherited classes
together in a file. That puts them in the same namespace, which makes
Cohesion is the flip side: if a class is large, even if it is somewhat
coupled to other classes, it should probably go in its own file. In
general, use coupling as a guide to put more things into a single
file, and cohesion as a guide to break out parts into multiple files.
More information about the Python-list