29

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?

EDIT: 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
    Limiting to one class per file is NOT a C++ thing. Java is the only language I know of where it's considered something to be avoided. In C++, it is extremely common for a single .h/.cpp file to have one primary class and lots of helper classes, which may or may not be private to the primary class. – Steven Burnap Aug 30 '13 at 15:33
  • @StevenBurnap I removed c++ as an example, as you are correct. – Ampt Aug 30 '13 at 15:41
  • 1
    It’s also done in php to facilitate auto-loading. On the other hand in php you can explicitly declare namespace. – bodo Nov 16 '16 at 7:56
21

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:

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

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

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

  • 2
    Your answer would be stronger if it cited external references demonstrating the normality of combining classes in one file, or by providing more explanation indicating why it's OK. – GlenH7 Aug 30 '13 at 15:37
  • 1
    I've edited the question to point out that this is simply an example of what I mean, and doesn't exactly represent the nature of the question. Why is keeping them in the same file better than simply importing them where needed? – Ampt Aug 30 '13 at 15:40
  • Having lots of tiny files can be as hard to manage as having a few giant files. Python is a fairly terse language. Your example shows this. Those three classes are directly related and likely fit in a single editor window without scrolling. – Steven Burnap Aug 30 '13 at 15:50
  • 1
    @GlenH7 - I'm not sure about the references, since they just shift from me making a claim directly, to me claiming that my selection bias is valid. I've tried to focus on the explanation instead. – Useless Aug 30 '13 at 16:19
7

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.

  • 7
    Could you reduce this down to the parts relevant to the question? I've read both of these multiple time but I'm having a hard time picking out which parts in particular relate to my current question. – Ampt Aug 30 '13 at 15:33
  • 1
    Indeed, I've edited my answer. – Josay Aug 30 '13 at 16:31
1

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

0

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.

-1

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.

  • 3
    this doesn't seem to add anything substantial over prior answer posted few years ago – gnat Jul 1 '14 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.