import from containing folder

Simon Forman rogue_pedro at yahoo.com
Wed Jul 26 11:49:36 EDT 2006


David Isaac wrote:
> Suppose I have inherited the structure
>
> PackageFolder/
>       __init__.py
>       mod1.py
>       mod2.py
>       SubPackageFolder/
>               __init__.py
>               mod3.py
>
> and mod3.py should really use a function in mod2.py.
> *Prior* to Python 2.5, what is the best way to access that?
> (Please assume that "move it" is not the answer.)
>
> Thanks,
> Alan Isaac

To play with this I created a directory 'delmepy' in
/usr/lib/python2.4/site-packages/ and gave it the following structure:

$ ls -R /usr/lib/python2.4/site-packages/delmepy
/usr/lib/python2.4/site-packages/delmepy:
__init__.py  mod2.py  subp
/usr/lib/python2.4/site-packages/delmepy/subp:
__init__.py  mod3.py

Both __init__.py's are empty, mod2.py looks like this:

def banana(n):
    print n

and mod3.py looks like this:

import delmepy.mod2
delmepy.mod2.banana(23)

The following (at the interactive prompt) worked fine:
>>> import delmepy.subp.mod3
23

I would assume (but I haven't checked) that this should work as long as
delmepy (in your case PackageFolder) was somewhere on sys.path.

HTH,
~Simon




More information about the Python-list mailing list