what's the general way of separating classes?
roy at panix.com
Mon Mar 20 17:11:28 CET 2006
John Salerno <johnjsal at NOSPAMgmail.com> wrote:
> From my brief experience with C#, I learned that it was pretty standard
>practice to put each class in a separate file. I assume this is a
>benefit of a compiled language that the files can then be grouped together.
>What I'm wondering is how is this normally handled in Python? Is it
>normal for classes to be put in separate modules? It seems like this can
>get out of hand, since modules are separate from one another and not
>compiled together. You'd end up with a lot of import statements.
>Are related classes put into a single module then? Or is there some
>recommended method for how to handle this?
There are two different issues here. One is how you organize your
source code, the other is what API you expose to the user.
>From the source code point of view, I will generally put a single
class in each file, but there are exceptions (no pun intended). If
I've got a bunch of very closely related classes, especially if
they're small, I'll put more than one class in a file. How small is
small? There's no hard number, but anything that's got more than a
couple of methods is probably not small. Exception classes certainly
don't get their own file; they get put in the module where they make
the most sense.
>From the API point of view, just because you split your classes up
into multiple modules, doesn't mean the user has to see that
complexity. Have one top level module which imports the others. The
user only has to import the top level one.
There's no magic answer here.
To give you a real example, I just took a look at a recent project I
did. I've got 8 python source files, totalling 1505 lines. I define
14 classes, of which 7 are exception classes. My top level module
(the one a user would import) has no classes defined in it; it imports
the other modules and has a bunch of factory functions. I looked at
the one file that contains two real classes; one of them is
essentially an inner class and has only two methods; __init__() and
__call__(), both of which are trivial.
More information about the Python-list