Thomas Thorogood
Thomas Thorogood

Reputation: 2357

VirtualEnv - Python 3.2 - Package gives ImportError (but not in 2.7)

I'm new to virtualenv, but the error I'm getting doesn't make any sense to me.

When I do pip install MultiString in my Python 2.7 virtualenv, i can then use the package without problems.

If I do the same in Python 3.2, the install runs as expected, but when trying to import, i get:

  File "<stdin>", line 1, in <module>
  File "/home/tom/p3/lib/python3.2/site-packages/multistring/__init__.py", line 1, in <module>
    from MultiString import MultiString
ImportError: No module named MultiString

Even though:

(p3)tom@K9:~$ ls -alh /home/tom/p3/lib/python3.2/site-packages/multistring/
total 28K
drwxrwxr-x 3 tom tom 4.0K Mar 22 11:44 .
drwxrwxr-x 7 tom tom 4.0K Mar 22 11:43 ..
-rw-rw-r-- 1 tom tom   36 Mar 22 11:43 __init__.py
-rw-rw-r-- 1 tom tom  12K Mar 22 11:43 MultiString.py
drwxrwxr-x 2 tom tom 4.0K Mar 22 11:43 __pycache__

If I cd into that directory and do python __init__.py from within the p3 virtualenv, there are no issues. Likewise, if I cd into that directory and open an interactive session, I'm able to import and use the library as usual.

The error message given reveals that it's finding the right package, but I don't get why it's unable to import it.

I tried adding /home/tom/p3/lib/python3.2/site-packages to the PATH environment variable, just in case, but it did not fix the issue.

I'm trying to use tox to test my library's compatibility with Python 3, and i haven't used Python 3 much, but I sense this is more an issue with virtualenv.

Upvotes: 1

Views: 157

Answers (1)

user707650
user707650

Reputation:

At a guess, this is a problem with the old (2.x) relative imports. __init__.py probably has

from MultiString import MultiString

while it should be

from multistring.MultiString import MultiString

or (I think)

from .MultiString import MultiString

But I believe the absolute import is preferred.

This is an issue I've stumbled upon several times when installing 2.x packages under 3.x. I don't know if the 2to3 tool fixes this (I've hacked the source codes manually).

Upvotes: 2

Related Questions