0

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?

1
  • Have you tried import foo as bar? Commented Jan 24, 2013 at 19:48

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.