In working with python for the first time, I’ve found that I end up writing multiple classes in the same file, which is opposed to other languages like Java, which uses one file per class.
Usually, these classes are made up of 1 abstract base class, with 1-2 concrete implementations who’s use varies slightly. I’ve posted one such file below:
class Logger(object):
def __init__(self, path, fileName):
self.logFile = open(path + '/' + filename, 'w+')
self.logFile.seek(0, 2)
def log(self, stringtoLog):
self.logFile.write(stringToLog)
def __del__(self):
self.logFile.close()
class TestLogger(Logger):
def __init__(self, serialNumber):
Logger.__init__('/tests/ModuleName', serialNumber):
def readStatusLine(self):
self.logFile.seek(0,0)
statusLine = self.logFile.readLine()
self.logFile.seek(0,2)
return StatusLine
def modifyStatusLine(self, newStatusLine):
self.logFile.seek(0,0)
self.logFile.write(newStatusLine)
self.logFile.seek(0,2)
class GenericLogger(Logger):
def __init__(self, fileName):
Logger.__init__('/tests/GPIO', fileName):
def logGPIOError(self, errorCode):
self.logFile.write(str(errorCode))
As seen above, I have a Logger
base class, with a couple of implementation differences below that.
The Question:
Is this standard for python, or for any language? What problems could arise from using this implementation if any?
Please note: I’m not really looking for guidance on this specific file, but in a more general sense. What if the classes ended up being 3-5 moderately complex methods? Would it make sense to split them then? Where is the cutoff for saying you should split a file up?
3
It’s fine. It’s fine in C++ as well, for reference.
Keeping tightly-coupled things together is sensible practice. Avoiding inappropriate coupling is also good practice. Striking the right balance isn’t a matter of strict rules, but of, well, striking a balance between different concerns.
Some rules of thumb:
-
Size
Excessively large files can be ugly, but that’s hardly the case here. Ugliness is probably a good enough reason to split a file, but developing that aesthetic sense is largely a matter of experience, so it doesn’t help you figure out what to do a priori
-
Separation of Concerns
If your concrete implementations have very different internal concerns, your single file accumulates all those concerns. For example, implementations with non-overlapping dependencies make your single file depend on the union of all those dependencies.
So, it might sometimes be reasonable to consider the sub-classes’ coupling to their dependencies outweighs their coupling to the interface (or conversely, the concern of implementing an interface is weaker than the concerns internal to that implementation).
As a specific example, take a generic database interface. Concrete implementations using an in-memory DB, an SQL RDBMS and a web query respectively may have nothing in common apart from the interface, and forcing everyone who wants the lightweight in-memory version to also import an SQL library is nasty.
-
Encapsulation
Although you can write well-encapsulated classes in the same module, it could encourage unnecessary coupling just because you have access to implementation details that wouldn’t otherwise be exported outside the module.
This is just poor style I think, but you could enforce better discipline by splitting the module if you really can’t break the habit.
4
My usual reference documents to know what is pythonic.
Simple is better than complex.
Flat is better than nested.
From The Zen Of Python
Almost without exception, class names use the CapWords convention.
Package and Module Names Modules should have short, all-lowercase
names. […] Module names are mapped to file names
From PEP 8
My interpretation is that it’s fine as it would keep things simple and flat.
Also, because class names and file names have different cases, they are not supposed to be identical anyway so I wouldn’t see any issue in packing multiple related classes in a file.
2
What you have now is fine. Go and browse the standard library – there’s plenty of modules with multiple related classes in a single file. At some point, things get bigger and you eventually will want to start using modules with multiple files but there’s no real rules as to when. Things just get split when one file starts feeling ‘too big’.
It is definitely okay and I would encourage you to have several classes in one file as long as they are realated. In general your classes should stay short and concise and you should rather split up behaviour in two or more classes than build huge monolithic ones. When writing several small classes it is really necessary and helpful to keep those that are related in the same file.
In short – hell yes.
Moreover, having multiple classes in a single file is sometimes very handy. Some packages (six
, bottle
) explicitly ship in a single file in order to easily be integrated into any third-party module without being pip installed (sometimes desirable). But, do make sure to organise your code well. Intensively use code comments and separation blocks in order to make it more readable.
1