[Tutor] using separate py files for classes

Steven D'Aprano steve at pearwood.info
Wed Nov 2 20:29:13 CET 2011


Chris Hare wrote:
> I would like to put each of my classes in separate files to make it
> easier to edit them and keep the various files as small as possible
> for editing purposes.

Perhaps you need a better editor, one with a class browser that lets you 
see the layout of your classes and the relationship between them.

Or perhaps you need smaller classes. I've seen people writing Java in 
Python, and their code ends up anything from 2 to 10 times bigger (and 
consequently slower) than necessary. "One class per file" is very much a 
Java thing.

But without actually seeing your classes, I can't judge.

> I have come across a couple of problems:
> 
> 1.  I have to use import statements like "from file import class"
> instead of "import file" 2.  I have to include all of the import
> statements for things not found in the class file
> 
> Is this normal or am I doing something wrong?

You may be doing something wrong. In Python, it is not normal to force 
the rule "one class per module". You wouldn't say "one method per 
class", would you? In Python, the normal rules are:

* put a group of related methods into a class
* put a group of related classes and functions into a module
* put a group of related modules into a package

Python is designed to work that way, and it is quite unusual to design 
your library or application to be different.



-- 
Steven


More information about the Tutor mailing list