6

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?

asked Feb 1, 2019 at 9:11
6
  • 1
    You certainly don't need to put every class in its own file. You can divide them up however makes sense for your project. Commented Feb 1, 2019 at 9:13
  • 1
    You don't need to in java either, but it's a strong convention. It's a good question: what is the established best practice in Python, in this respect? As far as I know, the answer is "it varies". Commented Feb 1, 2019 at 9:13
  • So it is fine in python to have classes starting by importing other classes they interact with/use/(inherit from?) ? Commented Feb 1, 2019 at 9:14
  • 4
    @alexis In Java you must put each public class in its own file. It's a real restriction, not just a convention. Commented Feb 1, 2019 at 9:15
  • ok, i stand corrected. Commented Feb 1, 2019 at 9:15

4 Answers 4

6

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.

user613
2434 silver badges13 bronze badges
answered Feb 1, 2019 at 10:02
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Alex
6551 gold badge5 silver badges10 bronze badges
answered Feb 1, 2019 at 9:30

Comments

1

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

answered Feb 1, 2019 at 9:35

Comments

-1

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.

answered Feb 1, 2019 at 9:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.