I apologize for yet another __init__.py
question.
I have the following package structure:
+contrib
+--__init__.py
|
+database
+--__init__.py
|
+--connection.py
In the top-level __init__.py
I define: USER='me'
. If I import contrib
from the command line, then I can access contrib.USER
.
Now, I want to access contrib.user
from withih connection.py
but I cannot do it.
The top-level __init__.py
is called when I issue from contrib.database import connection
, so Python is really creating the parameter USER
.
So the question is: how to you access the parameters and variables declared in the top-level __init__.py
from within the children.
Thank you.
EDIT:
I realize that you can add import contrib
to connection.py
, but it seems repetitive, as it is obvious (incorrectly so?) that if you need connection.py
you already imported contrib
.
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.
The sole purpose of __init__.py is to indicate that the folder containing this file is a package, and to treat this folder as package, that's why it is recommended to leave it empty.
The __init__.py file lets the Python interpreter know that a directory contains code for a Python module . An __init__.py file can be blank. Without one, you cannot import modules from another folder into your project. The role of the __init__.py file is similar to the __init__ function in a Python class.
If a file named __init__.py is present in a package directory, it is invoked when the package or a module in the package is imported. You can use this to execute package initialization code, for example for the initialization of package-level data.
Adding import contrib
to connection.py
is the way to go. Yes, the contrib
module is already imported (you can find out from sys.modules
). The problem is there is no reference to the module from your code in connection.py. Doing another import will give you the reference. You do not need to worry about additional loading time because the module is already loaded.
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