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__.pywhen 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:
Let’s say
__init__.pyhas the codeprint "Initializing __init__", andtestmod.pyhasprint "Initializing testmod". In that case, importingtestpackageortestmodwould cause the initialization code to be run:It doesn’t, however, give
testmod.pyaccess to the variables from__init__.py. This has to be done explicitly.