Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put a class definition into __init__.py?

Tags:

python

I have a package with a class structure similar to this. Base class is a typical, simple parent class for a few separate hierarchies.

My package layout looks like this:

__init__.py (empty)
base.py
ab.py
cd.py
ef.py

Is it a good idea or good practice to put Base class into __init__.py instead of creating separate module just for one class? In this way I wouldn't need to import it each time in modules.

like image 383
maln0ir Avatar asked Dec 10 '17 16:12

maln0ir


People also ask

What goes into __ init __ py?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

What is def __ init __?

__init__ method "__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.

Should I put code in init py?

So it's normally a good place to put any package-level initialisation code. The bottom line is: all names assigned in __init__.py , be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.

What is def __ init __( self in Python?

In this code: class A(object): def __init__(self): self.x = 'Hello' def method_a(self, foo): print self.x + ' ' + foo. ... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not.


1 Answers

It is perfectly fine and a more flexible approach to leave it in base.py. Also note that the primary use of __init__.py is to initialize Python packages and not to hold content.

To avoid having to import the module each time you can write something like

# in __init__.py
from .base import Base

into the __init__.py such that you can directly import Base from my_package:

# some script
from my_package import Base

This is a common approach to make objects available at the package level.

For more info about the __init__.py file check out the documentation.

like image 111
jojo Avatar answered Sep 29 '22 19:09

jojo