Why NOT only one class per file?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Apr 4 19:24:37 EDT 2007


Chris Lasher a écrit :
> 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, 

Why not ?

> 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,

With much more verbosity and boilerplate code...

> 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.

Bullshit. diff used to exist way before Java. And it's still used for 
languages that have no notion of 'class'. I use it on an almost daily 
basis, FWIW.

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

> He doesn't find my arguments convincing,

Then he's a bit on the masochist side.

> 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?

Because it just sucks.

Ok, let's have an example: I'm currently working on adding 
ActiveRecord-like validation to Elixir, and here's one of my classes:
"""
class ValidatePresenceOfStatement(ValidateWithStatement):
     def __init__(self, entity, column, when='on_save'):
         validator = validators.not_empty
         super(ValidateWithStatement, self).__init__(entity, column, 
validator, when)

validate_presence_of = Statement(ValidatePresenceOfStatement)
"""

Four (4) lines of code. Should I really consider putting this in a 
separate file ? And what about my functions, then ? Should they all live 
in a separate file  too?

FWIW, I'm also currently working on a Plone application developped by a 
(somewhat braindead) Java programmer, who of course did the 
'one-class-per-file' dance. *It's a pure nightmare*. I constantly have 
to switch between dozens of files to find things that are so obviously 
tied together that they should belong to a single module. In some cases, 
there's more import statements than effective code. Talk about a waste 
of time.

> Thoughts, comments, and insight much appreciated,

Just ask him why Java insists on 'one-(public)-class-per-file', and why 
it's considered good form in C++. I mean, the real *technical* reasons...



More information about the Python-list mailing list