Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access __init__.py variables from deeper parts of a package

Tags:

python

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.

like image 445
Escualo Avatar asked May 18 '10 19:05

Escualo


People also ask

What is the use of file __ init __ py in a package?

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 the use of file __ init __ py in a package even when it is empty?

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.

What does adding __ init __ py do?

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.

What is the purpose of __ init __ py file at the time of creating Python packages?

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.


1 Answers

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.

like image 194
Wai Yip Tung Avatar answered Sep 23 '22 15:09

Wai Yip Tung