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?
You’ve stumbled across a misfeature: relative imports. When you say
from couchdb.client..., Python first looks for a module underoffers.that’s namedcouchdb. 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:
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: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.)