A.D
A.D

Reputation: 438

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?

Upvotes: 5

Views: 17221

Answers (4)

Jab
Jab

Reputation: 27485

TLDR: Python doesn't limit you structurally, although following best practices make for a better coding experience. Python files should be a grouping of similar code and can be used in other files. This grouping is considered a module.


It can depend on the project/use-case, and how you want to structure your code/application. In Python, "Everything is an Object" cough cough including classes.

With this being said, if you go further to read in the docs, there are use cases where you would want to have multiple classes in the same file such as exceptions as they "are classes too"

For example exceptions.py:

class ApplicationError(Exception):
    pass

class LoadingError(Exception):
    pass

class ValidationError(ApplicationError):
    pass

Or if you have a class that overrides another

For example breeds.py:

class Dog:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def bark():
        return("Bark")

class Chihuahua(Dog):

    def bite_ankles():
        return("Pain")

What I have now made essentially are 2 python modules these help break a python application into bite size pieces.

As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.

Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

There's are cases where using multiple classes and definitions in one file can be handy but it depends on how you plan to structure your project. Sure you could put all your code into one file but this is difficult to manage and goes way against the Zen of Python "Readability Counts".

Here's the first excerpt from the documentation of classes:

Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3. Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.

Upvotes: 4

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

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.

Upvotes: 4

dejanualex
dejanualex

Reputation: 4328

When you structure your code in Python, it's useful to think in terms of namespaces (mapping from names to objects) : https://docs.python.org/3/tutorial/classes.html .

Then you can structure your code (depending on his complexity) in modules (file containing Python definitions and statements) and then packages (a way of structuring Python’s module namespace by using “dotted module names”): https://docs.python.org/3/tutorial/modules.html

Upvotes: 1

Pradeep Pandey
Pradeep Pandey

Reputation: 307

By default python did not create one file for each class in code file.

To create separate file for each class, it code of each class should be in separate file

If two classes are related or tightly coupled, and client code will need to instantiate each, It is good to put them in the same file.

If one parent class has many child classes, and child class has very little code, better to put in one file.

Upvotes: -1

Related Questions