Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to import python modules for an entire package?

I have a package structure that looks like this

├── Plugins
│   ├── Eight_Ball.py
│   ├── Ping.py
│   ├── Weather.py
│   ├── __init__.py

Every .py file inside the package needs to import a few modules from elsewhere in the project. I'd rather every file in the package didn't start with

from ..Utils.constants import Plugin_Type
from ..Models.Plugin import Plugin
from ..Models.Singleton import Singleton

so is there a way to have files in the Plugins package have those imports by default?

like image 662
TWOF Avatar asked Jan 27 '17 00:01

TWOF


People also ask

How import all modules from package?

Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.

How do I import an entire module?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

Can you import all in Python?

You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.

What are the ways to import modules in Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.


1 Answers

In short, no, there is no way to have files in the Plugins package import things by default.

Although it is generally discouraged to use from module import *, if you really wanted to save those few extra lines you could make a general import file that imports everything you need like this:

common_imports.py:

  from ..Utils.constants import Plugin_Type
  from ..Models.Plugin import Plugin
  from ..Models.Singleton import Singleton

other_files.py:

  from .common_imports import *

Again, using from module import * is discouraged, and I would recommend you simply include those few lines at the beginning of every file.

like image 195
BluCode Avatar answered Oct 13 '22 22:10

BluCode