Why are module access attributes not declared in __init__.py of their package?

I have a package structure as follows:

mypackage __init__.py mymodule.py 

I put some "persistent" ads in __init__.py , for example:

 DELIMITER='\x01' 

However, the code in the mymodule.py file cannot access DELIMITER unless I add:

 from __init__ import * 

To the beginning of the mymodule.py file. I guess I missed the concept here. Is this what declared in __init__.py not readable in memory until it is accessible through the import statement? Also, is this a typical type of thing to put in the __init__.py file?

+6
source share
2 answers

Python runs the code in __init__.py when the package is imported, which allows for some initialization. However, just because it is executed does not mean that you have access to the variables in it from other modules.

For instance:

 testpackage __init__.py testmod.py 

Let's say __init__.py has the print "Initializing __init__" code print "Initializing __init__" , and testmod.py has the print "Initializing testmod" . In this case, importing testpackage or testmod will testmod initialization code:

 dynamic-oit-vapornet-c-499:test dgrtwo$ python -c "import testpackage" Initializing __init__ dynamic-oit-vapornet-c-499:test dgrtwo$ python -c "from testpackage import testmod" Initializing __init__ Initializing testmod 

However, it does not give testmod.py access to the variables from __init__.py . This must be done explicitly.

+5
source

Packages in no way collapse all modules in them. There is no reason for the material in __init__ be available in other modules if you do not import it.

+2
source

Source: https://habr.com/ru/post/921796/


All Articles