I have a package structure as follows:
mypackage
__init__.py
mymodule.py
I put some "constant" declarations in __init__.py
for example:
DELIMITER='\x01'
However, the code in the mymodule.py can't access DELIMITER unless I add:
from __init__ import *
To the top of the mymodule.py file. I suppose I missed a concept here. Is it that whatever is declared in __init__.py
doesn't get read into memory until it is accessed via an import statement? Also, is this a typical type of thing to put into the __init__.py
file?
Python does run the code in __init__.py
when the package is imported, which allows some initialization to be done. However, just because it is run does not mean that you have access to the variables in it from within other modules.
For example:
testpackage
__init__.py
testmod.py
Let's say __init__.py
has the code print "Initializing __init__"
, and testmod.py
has print "Initializing testmod"
. In that case, importing testpackage
or testmod
would cause the initialization code to be run:
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
It doesn't, however, give testmod.py
access to the variables from __init__.py
. This has to be done explicitly.
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