I have a package, spam, that contains a contains the variable _eggs in __init__.py In the same package, in boiler.py, I have the class Boiler.
In Boiler, I want to refer to _eggs in the package’s __init__.py file. Is there a way that I can do this?
The most appropriate way to retrieve that value is via an explicit relative import:
However, one thing to keep in mind is that the following command line invocation will then fail to work:
The reason this won’t work is the interpreter doesn’t recognise any directly executed file as part of a package, so the relative import will fail.
However, with your current working directory set to the one containing the “spam” folder, you can instead execute the module as:
This gives the interpreter sufficient information to recognise where boiler.py sits in the module hierarchy and resolve the relative imports correctly.
This will only work with Python 2.6 or later – previous versions couldn’t deal with explicit relative imports from main at all. (see PEP 366 for the gory details).
If you are simply doing
import spam.boilerfrom another file, then that should work for any Python version that allows explicit relative imports (although it’s possible Python 2.5 may needfrom __future__ import absolute_importsto correctly enable this feature)