Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have a 2.6 python script and library in the following directory structure:

+ bin
\- foo.py
+ lib
\+ foo
 \- bar.py

i would like users to run bin/foo.py to instantiate the classes within lib/foo.py. to achieve this, in my bin/foo.py script i have the following code:

from __future__ import absolute_import
import foo
klass = foo.bar.Klass()

however, this results in:

AttributeError: 'module' object has no attribute 'bar'

ie it thinks that foo is itself rather than the library foo - renaming bin/foo.py to bin/foo-script.py works as expected.

is there a way i can keep the bin/foo.py script and import lib/foo.py?

share|improve this question
Have you tried import foo as bar? – Steve Peak Jan 24 at 19:48

2 Answers

up vote 2 down vote accepted

The current directory is on the path by default, so you need to remove that before you import the other foo module:

import sys
sys.path = [dir for dir in sys.path if dir != '']

Alternatively, prepend the lib directory so that it takes precedence:

import sys
sys.path = ['../lib'] + sys.path
share|improve this answer
great; that fixed it - thanks! – yee379 Jan 24 at 23:40

If you just write import foo, it will definitely load the foo module in the current scope. Assuming lib and foo as packages, won't you need to write something like this in order to make it work?

import lib.foo.bar as foobar
klass = foobar.Klass()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.