Using module's own objects in __main__.py

sharvey picture sharvey · Aug 5, 2010 · Viewed 13k times · Source

I’m trying to access a module’s data from inside its __main__.py.

The structure is as follows:

mymod/
    __init__.py
    __main__.py

Now, if I expose a variable in __init__.py like this:

__all__ = ['foo']
foo = {'bar': 'baz'}

How can I access foo from __main__.py?

Answer

pdemb picture pdemb · Aug 5, 2010

You need to either have the package already in sys.path, add the directory containing mymod to sys.path in __main__.py, or use the -m switch.

To add mymod to the path would look something like this (in __main__.py):

import sys
import os
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '..')
sys.path.insert(0, path)
from myprog import function_you_referenced_from_init_file

Using the -m switch would like:

python -m mymod

See this answer for more discussion.