Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't module access attributes declared in __init__.py of its package?

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?

like image 592
Sam Goldberg Avatar asked Jul 31 '12 19:07

Sam Goldberg


1 Answers

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.

like image 81
David Robinson Avatar answered Sep 21 '22 11:09

David Robinson