7

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?

Sam Goldberg
  • 6,711
  • 8
  • 52
  • 85
  • 4
    Where did you get the impression it would work without the `import` statement? – David Robinson Jul 31 '12 at 19:23
  • @DavidRobinson: From the Python documentation. ["__init__.py Initialize the sound package"](http://docs.python.org/tutorial/modules.html#packages). Not sure how else I would interpret what they are saying there, other than by assuming that code in __init__.py is initialized by Python. – Sam Goldberg Jul 31 '12 at 19:34

2 Answers2

5

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.

David Robinson
  • 77,383
  • 16
  • 167
  • 187
2

Packages don't somehow roll together all of the modules in them. There's no reason for stuff in __init__ to be accessible in the other modules unless you import it.

Marcin
  • 48,559
  • 18
  • 128
  • 201