3

I'm using python in virtualenv. I have following module:

offers/couchdb.py:

from couchdb.client import Server

def get_attributes():
    return [i for i in Server()['offers']]

if __name__ == "__main__":
    print get_attributes()

When I run it from file I get:

$ python offers/couchdb.py
Traceback (most recent call last):
  File "offers/couchdb.py", line 1, in <module>
    from couchdb.client import Server
  File "/Users/bartekkrupa/D/projects/commercial/echatka/backend/echatka/offers/couchdb.py", line 1,     in <module>
    from couchdb.client import Server
ImportError: No module named client

But when I paste it into interpreter... it works:

$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from couchdb.client import Server
>>> 
>>> def get_attributes():
...     return [i for i in Server()['offers']]
... 
>>> if __name__ == "__main__":
...     print get_attributes()
... 

What may be the couse that python running that module from file doesn't load couchdb module, but running in REPL does?

2 Answers 2

7

You've stumbled across a misfeature: relative imports. When you say from couchdb.client..., Python first looks for a module under offers. that's named couchdb. And it finds one: the file you're working on, offers/couchdb.py!

The usual fix is to disable this behavior, which is gone in Python 3 anyway. Put this as the first line of Python code in your file:

from __future__ import absolute_import

Then Python will assume you want to import from a top-level module named couchdb (which you do), not a sibling of the current module.

Unfortunately, in this case, you're running the file directly, and Python will still add offers/ to its search path. When running a file that's intended to be a module, you can run it with -m:

python -m offers.couchdb

Now it should work.

(You could, of course, just not name your file couchdb.py. But I find it's pretty useful to have modules named after the thing they interact with or wrap.)

Sign up to request clarification or add additional context in comments.

Comments

0

Edit: See Eevee's answer above - I think it fits better. Still, this might be helpful for others(?):

Maybe you did not install couchdb in your virtualenv? That could explain why it works in the interpreter (if the interpreter is not launched from the virtualenv.

Either install it there or create the virutalenv with --site-packages.

1 Comment

interpreter is launched from virtualenv for sure :)

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.