javapythonclasscompilationunit

Should a python file always include a class?


I have been coding in python for a couple months now, and something has always been on my mind. I know you can have classes in your .py file, but you don't have to. My question is, is it good practice to always have your code in a class, or is it not necessary?

FYI: I have been coding in Java for a few years, so I'm used to always having a "main" class and a main method that runs everything.


Solution

  • It depends on what your file is. In theory everything (saying this with some hesitation) can be written as a class. But it is a bit overkill to do that just for the sake of being "correct" and will probably make your code look strange rather than clear. In general i would make the following distinctions between cases

    1. If it is the source for a big project which makes sense to be organized in an object oriented fashion, then you would have a class which defines exactly that. This is great because then you can inherit the class for variants or child projects.
    2. If you are creating a list of utility functions to use for all your projects, such as array manipulations or little tools that are always handy, then a function-only file is the way to go
    3. If you are writing a script which is designed in order to execute a specific task in the way a script would, then i would define task-specific source in a .py file and include the code related to the execution under the statement

      if name == 'main':