tags:

views:

52

answers:

2

Hi, I am trying to access a module's own data inside it's __main__.py. The structure is as follow:

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?

+1  A: 

The __init__ module of a package acts like members of the package itself, so the objects are imported directly from mymod:

from mymod import foo

Or

from . import foo

if you like to be terse, then read about relative imports. You need to make sure, as always, that you do not invoke the module as mymod/__main__.py, for example, as that will prevent Python from detecting mymod as a package. You may wish to look into distutils.

jleedev
I wanted to make the module directory executable.
sharvey
Yeah I've tried these suggestions and they didn't work for me.
Matt Joiner
When I use `from . import foo`, I get a `ValueError: Attempted relative import in non-package`, and `ImportError: No module named mymod` otherwise.
sharvey
+2  A: 

You need to have the package in sys.path. Python behavior is consistent here. In that particular case, the easiest portable way to do it is 'sys.path.append (os.getcwd ())', which will add current directory to system module search path. The default Python behavior is to add the script file directory to this search path.

pdemb
adding `sys.path.append(os.getcwd())` before `from mymod import foo` worked perfectly, thanks
sharvey