Python: one single module (file .py) for each class?

It's not wrong to have one class per file at all. Python isn't directly aimed at object oriented design so that's why you can get away with multiple classes per file.

I recommend having a read over some style guides if you're confused about what the 'proper' way to do it is.

I suggest either Google's style guide or the official style guide by the Python Foundation

You can also find more material relating to Python's idioms and meta analysis in the PEP index


one file for each class

Do not do this. In Java, you usually will not have more than one class in a file (you can, of course nest).

In Python, if you group related classes in a single file, you are on the safe side. Take a look at the Python standard library: many modules contain multiple classes in a single file.

As for the why? In short: Readability. I, personally, enjoy not having to switch between files to read related or similar code. It also makes imports more concise.

Imagine socketserver.py would spread UDPServer, TCPServer, ForkingUDPServer, ForkingTCPServer, ThreadingUDPServer, ThreadingTCPServer, BaseRequestHandler, StreamRequestHandler, DatagramRequestHandler into nine files. How would you import these? Like this?

from socketserver.tcp.server import TCPServer
from socketserver.tcp.server.forking import ForkingTCPServer
...

That's plain overhead. It's overhead, when you write it. It's overhead, when you read it. Isn't this easier?

from socketserver import TCPServer, ForkingTCPServer

That said, no one will stop you, if you put each class into a single file. It just might not be pythonic.


Python has the concept of packages, modules and classes. If you put one class per module, the advantage of having modules is gone. If you have a huge class, it might be ok to put this class in a separate file, but then again, is it good to have big classes? NO, it's hard to test and maintain. Better have more small classes with specific tasks and put them logically grouped in as few files as possible.