Why NOT only one class per file?

Chris Lasher chris.lasher at gmail.com
Wed Apr 4 17:23:19 EDT 2007


A friend of mine with a programming background in Java and Perl places
each class in its own separate file in . I informed him that keeping
all related classes together in a single file is more in the Python
idiom than one file per class. He asked why, and frankly, his valid
question has me flummoxed.

I tried to rationalize this Python idiom by claiming a file--a single
module--makes for a great container of code which is logically tied
together, such as a class and its subclasses. He posited that
directories (packages) can tie the files together just as well, and by
having the classes as separate files, he can "diff" them to see how
they differ, something he wouldn't be able to do with the code all in
one file.

I also offered that having related classes under one file gives more
direct access to those classes, e.g.:

----------------------------------
file: foo.py
===
class Bar(object):
    pass
===

file demo1.py
===
import foo

barinstance = foo.Bar()
===
----------------------------------

versus

----------------------------------
file: foopkg/bar.py
===
class Bar(object):
    pass
===

file: demo2.py
===
import foopkg.bar

barinstance = foopkg.bar.Bar()
===
----------------------------------

He doesn't find my arguments convincing, so I thought I'd ask here to
see why the Python idiom is the way it is: why should we NOT be
placing classes in their own separate files?

Thoughts, comments, and insight much appreciated,
Chris




More information about the Python-list mailing list