pythonstructure

Python code structure for class organization


In Java the code is structured in packages with you each class in a separate file. Is there any similar practice in python? Is it better to have each class in a different python file and have them import each other or should I just dump my code(all my classes) in a single file?


Solution

  • In Java the code is structured in packages with you each class in a separate file. Is there any similar practice in python?

    Definitely no. Actually, Python doesn't force you to put all your code in classes - plain functions are ok too - so even the "each class" premise doesn't make sense.

    Is it better to have each class in a different python file

    Definitely no either - it would just make your code a nightmare to maintain.

    or should I just dump my code(all my classes) in a single file?

    Neither (unless it's a very small app). You want to regroup your code (functions, classes, etc.) in cohesive, decoupled modules/packages, which is the known best practice in all languages anyway. If you have a "full" app with domain code, persistence and UI you'll probably want to use this as your first level packages.