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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With