import from containing folder

D

David Isaac

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
 
S

Simon Forman

David said:
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: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
 
D

David Isaac

Simon said:
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.

Sorry that was not clear:
I do not want to make any assumptions about
this particular package being on sys.path.
(I want a relative import, but cannot assume 2.5.)

Thanks,
Alan
 
D

David Isaac

Alan said:
I do not want to make any assumptions about
this particular package being on sys.path.
(I want a relative import, but cannot assume 2.5.)


I should mention that to get around this I have
been using
sys.path.append(os.path.split(sys.argv[0])[0])
in the script I care most about. It works,
but seems like a hack.

Thanks,
Alan Isaac
 
S

Simon Forman

David said:
Alan said:
I do not want to make any assumptions about
this particular package being on sys.path.
(I want a relative import, but cannot assume 2.5.)


I should mention that to get around this I have
been using
sys.path.append(os.path.split(sys.argv[0])[0])
in the script I care most about. It works,
but seems like a hack.

Thanks,
Alan Isaac

Hack or not, that's what I would do. In fact I have done that. I hope
if there's a better way that someone will post it here. ;-)

Peace,
~Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top