Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to re-export modules from __init__.py

I have a plugins package that contains several modules, each defining one class (each class is a plugin).

My package structure looks like this :

plugins
├ __init__.py
├ first_plugin.py
├ second_plugin.py
└ third_plugin.py

And a plugin file typically looks like this, only containing a class definition (and a few imports if necessary) :

# in first_plugin.py

class MyFirstPlugin:
    ...

I would like the end user to be able to import a plugin like so :

from plugins import FirstPlugin

instead of having to also type the module name (which is what is currently required to do) :

from plugins.first_plugin import FirstPlugin

Is there a way to achieve this by re-exporting the modules' classes directly in the __init__.py file without having to import everything module by module like so (which becomes cumbersome when there are lots of modules) :

# in __init__.py

from .first_plugin import FirstPlugin
from .second_plugin import SecondPlugin
from .third_plugin import ThirdPlugin
like image 891
Ewaren Avatar asked Feb 27 '20 20:02

Ewaren


People also ask

What does __ init __ py do in Python?

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 should __ init __ py contain?

The gist is that __init__.py is used to indicate that a directory is a python package. (A quick note about packages vs. modules from the python docs: "From a file system perspective, packages are directories and modules are files.").

Does init py import all modules?

We can turn this directory into a package by introducing __init__.py file within utils folder. Within __init__.py , we import all the modules that we think are necessary for our project.


1 Answers

I do not think this is possible in Python. However you can import entire modules so you do not have to import each class individually.

For example

from first_plugin import *

Allowing you to do

from plugin import # Anything in first_plugin

Its kinda a pain but writing libraries is not easy (wait till you use CMake with C/C++, you have to specify every single file in your source tree :D)

like image 145
Object object Avatar answered Sep 21 '22 21:09

Object object