Pugsley
Pugsley

Reputation: 1446

Access to modules/objects within package w/o explicit import

Say, I have this structure on my file system: f/o/o/bar.py. How can I access bar.py contents nice & easy? From what I can tell, I can't simply use:

import f #Presumably sets initial point from where to search.
print(f.o.o.bar.object)

In this case import f will seek vars inside f's __init__.py.

When I use the code below, it works, but it seems that I have to use such imports for every module:

import f.o.o.bar
print(f.o.o.bar.object)

So, is there any easier and simpler way to work with packages, like the one below:

import sys
print(sys.argv)

Athough 'argv' haven't been imported explicitly, we can access it.

P.S. It seems that the issue was with Python itself: @ 2.7.5 everything worked as it should, but @ 3.2.5, 3.3.2 he caused errors.

Upvotes: 1

Views: 124

Answers (2)

bogatron
bogatron

Reputation: 19169

If you want them automatically imported, then you need to specify that in the __init__.py files:

# f/__init__.py:
import o

# f/o/__init__.py:
import o

# f/o/o/__init__.py:
import bar

# f/o/o/bar.py:
object = 3

Then:

>>> import f
>>> f.o.o.bar.object
3

[EDIT]: The code above applies to python 2.x. Since you want to use python 3.x, you should replace each of the import statements above with "from . import" (which will also work with python 2.7). For example:

# f/__init__.py:
from . import o

Upvotes: 3

Henry Keiter
Henry Keiter

Reputation: 17168

You can just use a from module import baz statement.

from f.o.o.bar import baz
print baz

Make sure you've got an __init__.py file in each subdirectory, to mark those directories as packages that Python should look into. This is what my testing directory looks like:

C:\test\
    f\
        __init__.py # empty
        o\
            __init__.py # empty
            o\
                __init__.py # empty
                bar.py # contains the line: baz = 3

Then in a command window:

C:\test>python
Python 2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from f.o.o.bar import baz
>>> baz
3

Note that I'm running the interpreter with C:\test as the working directory. Python looks in the current directory for modules and packages (in this case we want it to find the package called f). If you're accessing the packages/modules from somewhere else, say C:\somewhere\else, you need to make sure that C:\test (the directory containing the package) appears on your PYTHONPATH.


If you want to automatically import things (so you can just import f and get all the submodules), you can set that up in each __init__.py by putting import statements into those from the next directory down. Be careful when doing this, though, that you don't fill up your module namespaces with unnecessary or contradictory things.

Upvotes: 2

Related Questions