Search code examples
pythonfileclassmoduleconventions

One single module (file .py) for each class?


I've started programming in Python two weeks ago. I'm making a separate file (module) for each class as I've done before in languages like Java or C#.

But now, seeing tutorials and code from other people, I've realized that many people use the same files to define more than one class and the main function, but I don't know if they do it like that because are just examples or because it's a Python convention or something like that (to define and group many classes in the same files).

So, in Python, one file for each class or many classes in the same files if they can be grouped by any particular feature? (Like motor vehicles by one side and just vehicles by the other side).

It's obvious that each one has his own style, but when I ask, I hope general answers or just the conventions, anyway, if someone wants to tell me his opinion about his own style and why, feel free to do it!


Solution

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