Why NOT only one class per file?

D

Dillon Collins

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?

Because it really just provides as an artificial limitation that could only be
annoying at best? After all, programmers can put one class per file if the
want anyway.

I know I would like Python less if I had to make a directory of files each
with somehing like:

class MyError(Exception):
pass

Of course, there are other cases as well where logically grouping classes is
much nicer. However, at the end of the day the question is almost
meaningless because of the way Python treats classes.
Examples:

class A(object):
class B:
pass
C=A.B

class A(object):
pass
A=1

class A(object):
pass
B=type('B', (object,), {})


The first creates a class with a contained class, but then "exports" the
contained class as C. The second creates class A, but then destroys it by
writing over it with the value 1. The third also creates a class A, but this
time creates a top-level class B. You'll note that the method of
construction allows for B to be created dynamically.

So the idea of one class per file is almost meaningless.
 
C

Chris Lasher

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
 
J

Jarek Zgoda

Chris Lasher napisa³(a):
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'd not try to rationalize it, it's just natural. The requirement to
have only one public class per module needs rationalization (other than
limitation of compiler), not the freedom to have as much of classes in
module as is needed by program's architecure.
 
S

Steve Holden

Jarek said:
Chris Lasher napisa³(a):


I'd not try to rationalize it, it's just natural. The requirement to
have only one public class per module needs rationalization (other than
limitation of compiler), not the freedom to have as much of classes in
module as is needed by program's architecure.
The fact that your friend find being able to diff his classes valuable
implies that he isn't taking much advantage of modularity anyway but
instead using copy-and-paste techniques. Of course I may be doing him a
disservice.

In Java *everything* has to be in a class, unlike in Python. The module
seems a much more natural unit of storage to me, and to force us to put
each class in its own module would seem unnatural.

regards
Steve
 
?

=?ISO-8859-1?Q?Thomas_Kr=FCger?=

Chris said:
why should we NOT be
placing classes in their own separate files?

Thoughts, comments, and insight much appreciated,

At first: if he really like it he can place every class in a single
file. But there are some reasons why Python "allows" you to place many
classes in one file:

- It's (a little bit) faster, no additional file system lookup is needed. ;)
- You can define a class in a class. Django, for example, uses this for
it's data models. If you do this you are forced to have multiple classes
in on file. Example:
http://www.djangoproject.com/documentation/tutorial02/#make-the-poll-app-modifiable-in-the-admin

See also:
http://mail.python.org/pipermail/python-list/2006-December/418363.html

Thomas
 
K

Klaas

At first: if he really like it he can place every class in a single
file. But there are some reasons why Python "allows" you to place many
classes in one file:

- It's (a little bit) faster, no additional file system lookup is needed. ;)
- You can define a class in a class. Django, for example, uses this for
it's data models. If you do this you are forced to have multiple classes
in on file. Example:http://www.djangoproject.com/documentation/tutorial02/#make-the-poll-...

That is somewhat specious: inner classes can be defined in java too.

The main reason is that in java, classes are magical entities which
correspond to one "exportable" unit of code. Thus it makes a great
deal of sense to limit to one _public_ class per file (java also
allows unlimited private and package-private classes defined in a
single file).

If you want to define a bunch of utility functions in java, you write
a file containing a single class with static methods.

In python, classes do not have special status. The exportable unit of
code is a module, which, like public classes in java, can contain
functions, static variables, and classes. Similar to java, you are
limited to a single module object per file (modulo extreme trickery).

If you want to define a bunch of utility functions in python, you
write a file containing a single module with functions.

-Mike
 
F

Fuzzyman

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.

Only tightly coupled (and short) classes and functions.

It is better to keep modules as short as possible (and classes to),
without being ridiculous.

It is kind of obvious that keeping stub classes (exceptions for
example) in the same file is a good thing.

Diffing classes doesn't seem like a terribly good use-case: classes
that are *that* similar badly need refactoring into less classes...

Fuzzyman
http://www.voidspace.org.uk/python/articles.shtml
 
F

Fuzzyman

That is somewhat specious: inner classes can be defined in java too.

The main reason is that in java, classes are magical entities which
correspond to one "exportable" unit of code. Thus it makes a great
deal of sense to limit to one _public_ class per file (java also
allows unlimited private and package-private classes defined in a
single file).

If you want to define a bunch of utility functions in java, you write
a file containing a single class with static methods.

In python, classes do not have special status. The exportable unit of
code is a module, which, like public classes in java, can contain
functions, static variables, and classes. Similar to java, you are
limited to a single module object per file (modulo extreme trickery).

If you want to define a bunch of utility functions in python, you
write a file containing a single module with functions.

So Python has one less level of enforced nesting. :)

Fuzzyman
http://www.voidspace.org.uk/python/articles.shtml
 
B

Bruno Desthuilliers

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

Terry Reedy

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

Ask him why he does not wear a straightjacket all the time.
It is great for one's posture ;-)
 
S

Sherm Pendley

Bruno Desthuilliers said:
Chris Lasher a écrit :


Because it just sucks.
....

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

Yeah, as if "because it just sucks" is a technical reason. :)

It's a stylistic thing, nothing more. There's no technical basis for it,
just personal preference.

sherm--
 
D

Dennis Lee Bieber

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.
As I recall, Java essentially doesn't offer a CHOICE... So I'd
consider any argument that "one per file" is best to be flawed if based
upon Java practice. After all, if one can not even experiment with other
ways, how can one really evaluate the options? {and I consign Perl to
realms described by Dante}
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
H

Hendrik van Rooyen

Terry Reedy said:
Ask him why he does not wear a straightjacket all the time.
It is great for one's posture ;-)

No it isn't - those funny arms give you round shoulders..

- Hendrik
 
S

Steven Howe

Dennis said:
As I recall, Java essentially doesn't offer a CHOICE... So I'd
consider any argument that "one per file" is best to be flawed if based
upon Java practice. After all, if one can not even experiment with other
ways, how can one really evaluate the options? {and I consign Perl to
realms described by Dante}
On class per file was easier to do when Java was developed (remember it
was develop to control
vending machines; scary. Reminds me of the movie 'Tron'). The desktop
computer for Sun
was an IPC workstation. Nice but no balls and no good editors that
could have 24+ tabs open or
a way to 'close' sections of coherent text (which are common in my
preferred editor, Komodo).

So your friend is arguing the past. Ask him if he's a Republican too or
needs a serious reboot.
I have a good pair of boot to give him a kick in the ass (Democrats
would need a kick in the head
to reset; we all know what organ Republican think with).
sph
 
B

Bruno Desthuilliers

Sherm Pendley a écrit :
Yeah, as if "because it just sucks" is a technical reason. :)

It doesn't pretend to be one !-)
It's a stylistic thing, nothing more.

A bit more than just 'stylistic' IMHO. It's a matter of convenience.
Having to manage hundreds of files each with a dozen lines of code is a
PITA. Having to retype the same import statements in hundreds of files
is a PITA - and a good way to waste time and forget something when one
has to fix these import statements (yes, even with the appropriate
tediting tools). I wouldn't call such considerations "nothing more than
stylistic".
There's no technical basis for it,

No, but there's no technical reason for putting each class in a separate
file.
just personal preference.

True, I prefer to avoid boilerplate proliferation, switching-file-dance,
and maintenance nightmares.
 
C

Christophe

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, and frankly, his valid
question has me flummoxed.

In Java, you HAVE to place a class in it's own file. That's how the
language works. But in Java, you do not have to place each class in it's
own module/package, in fact, it would be bad.

It's the same in Python: you do not want to have one class per
module/package.

Unfortunately, in Python, a module/package is a file, and in Java, it's
a directory. Also, Python doesn't really have the notion of a "root
package/module".




Translation: "import foo; foo.foo()" sucks so avoid having only one
class per module :)
 
S

Sherm Pendley

Steven Howe said:
On class per file was easier to do when Java was developed (remember
it was develop to control vending machines

Not quite. Java grew out of a set-top box at Sun, code-named "Oak".
; scary. Reminds me of the movie 'Tron'

Vending machines in "Tron" were pussycats compared to the one in "Maximum
Overdrive." :)

sherm--
 
S

Steve Holden

Christophe said:
Chris Lasher a écrit :

In Java, you HAVE to place a class in it's own file. That's how the
language works. But in Java, you do not have to place each class in it's
own module/package, in fact, it would be bad.

It's the same in Python: you do not want to have one class per
module/package.

Unfortunately, in Python, a module/package is a file, and in Java, it's
a directory. Also, Python doesn't really have the notion of a "root
package/module".

Translation: "import foo; foo.foo()" sucks so avoid having only one
class per module :)

One further thought:

http://www.artima.com/weblogs/viewpost.jsp?thread=42242

regards
Steve
 
S

Sherm Pendley

Bruno Desthuilliers said:
Sherm Pendley a écrit :


A bit more than just 'stylistic' IMHO. It's a matter of
convenience. Having to manage hundreds of files each with a dozen
lines of code is a PITA.

Yes, but the pain in that case comes from having hundreds of trivial
classes, not from the way in which the source for them is organized.
Having to retype the same import statements
in hundreds of files is a PITA - and a good way to waste time and
forget something when one has to fix these import statements (yes,
even with the appropriate tediting tools). I wouldn't call such
considerations "nothing more than stylistic".

Neither would I. But then, I would describe the existence of all those
files as just the symptom - the real problem being the design that needs
all of those hundreds of trivial classes in the first place.

Granted, I know very little of Python. It may be the case that Python
encourages the use of hundreds of "little classes" - and if that is the
case, then I agree, storing each one in its own file would be rather
absurd.

I'm more accustomed to writing classes that tend to be larger - hundreds
if not thousands of lines each, or more - and in that case, storing them
one per file is a reasonable way to organize one's sources.

sherm--
 
N

Nate Finch

So, here's a view from a guy who's not a python nut and has a long
history of professional programming in other languages (C++, C, C#,
Java)

I think you're all going about this the wrong way. There's no reason
to *always* have one class per file. However, there's also no reason
to have 1600 lines of code and 50 classes in one file either. You
talk about the "changing file dance", but what about the "scroll for
30 seconds" dance? What about the "six different conflicts in source
control because everything's in one file" dance?

I think it doesn't matter how many classes and/or functions you have
in one file as long as you keep files to a reasonable size. If you've
ever worked on a medium to large-scale project using multiple
developers and tens or hundreds of thousands of lines of code, then
you know that keeping code separate in source control is highly
important. If I'm working on extending one class and someone else is
working on another class... it's much less of a headache if they're in
separate files in source control. Then you don't have to worry about
conflicts and merging. I think that's the number one benefit for
short files (not necessarily just one class per file).

My cutoff is around 500 lines per file. If a file goes much over
that, it's really time to start looking for a way to break it up.

Sure, if all your classes are 4 lines long, then by all means, stick
them all in one file. But I don't think that's really any kind of
valid stance to argue from. Sure, if you don't need organization, it
doesn't matter what organization technique you use. But if you do
need organization, it does matter. And I think one class per file is
an acceptable way to go about it, especially when your classes tend to
be over a couple hundred lines long.

-Nate
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top