473,388 Members | 1,480 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

One class per file?

HCB
Hello:

The book "Code Complete" recommends that you put only one class in a
source file, which seems a bit extreme for me. It seems that many
classes are small, so that putting several of them in a file seems
reasonable. I noticed that the decimal.py module in the standard
library has several classes, all of which of course revolve around the
"decimal" topic. Perhaps a better rule of thumb is "one idea per
file." I checked the Python style guide and there seems to be no
mention of this topic. I know this is an elementary question, but what
is the Python way of doing this?

Thanks for your time.
HCB
Sep 29 '08 #1
10 2485
HCB <hy*******************@gmail.comwrites:
The book "Code Complete" recommends that you put only one class in a
source file, which seems a bit extreme for me.
For Python, that is extreme, and for most applications I've seen it
would be counterproductive. Which edition of Code Complete recommends
this, and on which page?
Perhaps a better rule of thumb is "one idea per file." I checked the
Python style guide and there seems to be no mention of this topic. I
know this is an elementary question, but what is the Python way of
doing this?
You have it right: modules are most naturally used for conceptual
grouping of objects (not just classes, but all objects) related to a
discrete area of functionality, into a discrete namespace.

--
\ “The WWW is exciting because Microsoft doesn't own it, and |
`\ therefore, there's a tremendous amount of innovation |
_o__) happening.” —Steve Jobs |
Ben Finney
Sep 29 '08 #2
On Mon, 29 Sep 2008 06:12:35 -0700, HCB wrote:
Hello:

The book "Code Complete" recommends that you put only one class in a
source file, which seems a bit extreme for me. It seems that many
classes are small, so that putting several of them in a file seems
reasonable. I noticed that the decimal.py module in the standard library
has several classes, all of which of course revolve around the "decimal"
topic. Perhaps a better rule of thumb is "one idea per file." I checked
the Python style guide and there seems to be no mention of this topic. I
know this is an elementary question, but what is the Python way of doing
this?

Thanks for your time.
HCB
That sounds terrible! Imagine having a million source files to edit,
rename, create, delete each time you make a change. Sure, every Java fan
can give you a million reasons why the universe will collapse otherwise,
but this is totally impractical in python. Python's module organization
and namespaces are more than enough if used reasonably.
Sep 29 '08 #3
The book "Code Complete" recommends that you put only one class in a
source file, which seems a bit extreme for me. It seems that many
classes are small, so that putting several of them in a file seems
reasonable. I noticed that the decimal.py module in the standard
library has several classes, all of which of course revolve around the
"decimal" topic. Perhaps a better rule of thumb is "one idea per
file." I checked the Python style guide and there seems to be no
mention of this topic. I know this is an elementary question, but what
is the Python way of doing this?

I'm in a similar situation. I've been reading Robert C. Martins book
"Agile Software Development" and he suggests something similar. I
would highly recommend that book by the way. He also has a couple of
chapters on packaging where he makes some very good points about the
reasoning behind it. Basically that you want to organize your code in
such a way that package dependencies move in the direction of
increasing stability. In this case stability is a metric which is
defined as how likely the code is going to change in the future as
determined by how many packages depend on it as opposed to how many
packages it depends on. He paints a couple of scenarios in which he
groups packages together that _seem_ to be related, only to see that
it results in all of his packages needing to be re-built every time a
change is required. Obviously we don't have to re-build python code,
but it is still useful to organize your code in such a way that you
don't have to constantly re-visit collections of code.

I have actually started using his suggestion and have been putting one
class per file. When one class depends on another I include it with a
"from x import X". This makes it very easy to determine the
dependencies (well, the non-abstract dependencies anyway, interfaces
are a different story*). Then I put all of my classes together in a
package, and make the "public" classes visible on a package level by
importing them into the package __init__ module.

With that being said, If I made a class that was _only_ used by one
other single class, and it was clear that it would never be made
visible outside of that file, I would certainly put it in the same
file as that class. Heck, you might even refactor your code and
determine at that time that some piece of code is only used by one
other piece. It is much easier to put code together after the fact
than it is to separate it, especially later in the game.

My advice: don't knock it until you try it. I think my code has
improved quite a bit since taking this advice. It can be much more
difficult to determine which classes to package together until much
later in the development cycle. One thing that can help is to find an
IDE that helps you to easily switch between files. I use WingIDE, but
I have even used vim with a tags file and it wasn't terrible. I
wouldn't call it a hard rule, but at the same time I wouldn't just
ignore it. Give it a shot and adapt your development technique to see
what works best for you.

Example:

[mypackage/__init__.py]
__all__ = ["X"]

from .x import X
[end mypackage/__init__.py]

[mypackage/x.py]
from .y import Y

__all__ = ["X"]

class X(object):
# code - using Y hopefully
[end mypackage/x.py]

[mypackage/y.py]
__all__ = ["Y"]

class Y(object):
# code
[end mypackage/y.py]
Matt

* Interfaces in python represent an implicit dependency. The Zen of
Python states: "Explicit is better than implicit". I plan to
experiment with the ABC module in python 2.6/3.0. I want to make my
interfaces explicitly defined, but on the other hand I still want it
to be easy for people who use my code to duck-type. This _seems_ to be
possible since you can .register a class with an interface after it
has been created, but I'm not sure that it is very pythonic to
explicitly check for an interface every time it is used. It would seem
silly however to import an interface into a file where it isn't
explicitly used just to document the dependency. If anybody has
pointers let me know.
Sep 29 '08 #4
2008/9/29 Roy Smith <ro*@panix.com>:
That being said, the "one class per file" rule is a means to an end.
Although in some languages, the "end" is "code that runs". But Python
is not Java...

--
Tim Rowe
Sep 29 '08 #5
HCB
To answer Ben Finney's questions:

The "Put one class in one file" statement is made in "Code Complete 2"
page 771.

HCB

Sep 29 '08 #6
In message
<a9**********************************@34g2000hsh.g ooglegroups.com>, HCB
wrote:
The book "Code Complete" recommends that you put only one class in a
source file ...
That would only apply to languages like C with no namespace control.
Oct 1 '08 #7
Lawrence D'Oliveiro a crit :
In message
<a9**********************************@34g2000hsh.g ooglegroups.com>, HCB
wrote:
>The book "Code Complete" recommends that you put only one class in a
source file ...

That would only apply to languages like C with no namespace control.
classes in C ?-)

OTHO, 'one class per file' is a standard idiom in Java and IIRC in C++
(which both have namespaces one way or another)
Oct 1 '08 #8
Bruno Desthuilliers wrote:
OTHO, 'one class per file' is a standard idiom in Java and IIRC in C++
(which both have namespaces one way or another)
In Java you don't get a choice, because the compiler
assumes a class can be found in the correspondingly
named file.

While C++ has namespaces, they don't have any defined
relationship to source files, so they don't help you
find which file something is defined in.

--
Greg
Oct 3 '08 #9
On Oct 3, 1:51*pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
greg a crit :
Bruno Desthuilliers wrote:
OTHO, 'one class per file' is a standard idiom in Java and IIRC in C++
(which both have namespaces one way or another)
In Java you don't get a choice, because the compiler
assumes a class can be found in the correspondingly
named file.

For public classes only.
While C++ has namespaces, they don't have any defined
relationship to source files, so they don't help you
find which file something is defined in.

Nope. But IIRC, one-class-per-file helps saving on compile/link time. A
problem we don't have with dynamic languages !-)
I think that one goes in the 'handcuffs' category. You are free to
adopt the idiom if you want, aren't required to. (Though doesn't the
freedom handcuff later users of your code?)

Besides, it's not always clear what method in an inheritance tree is
getting called, so 'one class per file' doesn't guarantee you can find
an operation.

With 'exec( "class %s:\n..." )' statements and 'def f(): / class X: /
return X' statements, you don't even know all your classes at
startup. And not to mention 'namedtuple's certainly make the idiom
impractical in at least corner cases.

(But, when you need code and can't find discipline, maybe 'inside-the-
box' restrictions can bring your goal closer, no?)
Oct 4 '08 #10
Bruno Desthuilliers wrote:
Nope. But IIRC, one-class-per-file helps saving on compile/link time. A
problem we don't have with dynamic languages !-)
That's mostly true. Although I've noticed that if I have
a very large .py file, it can take a noticeable number
of moments to regenerate the .pyc after I've changed
something.

--
Greg
Oct 5 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Lpher Cypher | last post by:
Ok, here's what I'm trying to do. I have a class. Inside the class I have a method that reads a text file. In the text file I have a class name and a file name where that class is defined. Now, I...
8
by: Fu Bo Xia | last post by:
the java.lang.Object.forName method takes a java class name and returns a Class object associated with that class. eg. Class myClass = Object.forName("java.lang.String"); by if i only know the...
4
by: Hal Vaughan | last post by:
I want to have a config file for my program, which means I need to know where the config file is. If I type: java myclass and it runs myclass.class, is there any way to obtain the location of...
2
by: Pierre Rouleau | last post by:
Greetings, I'm wondering why the >> operator does not use the write() method of a class derived from the built-in file class as in DerivedFile below. In the following example: - StringFile...
10
by: Not Available | last post by:
On the host server: namespace JCart.Common public class JCartConfiguration : IConfigurationSectionHandler private static String dbConnectionString; public static String ConnectionString { get...
16
by: pawel.pabich | last post by:
Hajo, I would like to have 2 my own partial classes. For example: Default.aspx.cs Default2.aspx.cs and they both will relate to Default.aspx page.
0
by: Daniel Slen Secches | last post by:
I found a good class to do a simple FTP. Very good.... I'm posting it with the message, i hope it helps someone ============================================================== Imports...
4
by: joe | last post by:
I have the following header file generated by Java JNI's header file generator (see bottom). Obviously I will write a source file which will provide an implementation of these methods. I have...
7
by: tshad | last post by:
I have a problem with a VS 2003 project. This project was designed and works fine in VS 2003. But trying to open the project I get the following error....
4
by: alacrite | last post by:
I have a class that I want to turn its contents into csv file. I want to be able to set the value of the delimiter, the name of the file it gets saved to, the path of that file, and maybe a few...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.