Reputation: 1438
I have a python (2.7) project containing my own packages util and operator (and so forth).
I read about relative imports, but perhaps I didn't understand. I have the following directory structure:
top-dir/
util/__init__.py (empty)
util/ua.py
util/ub.py
operator/__init__.py
...
test/test1.py
The test1.py
file contains
#!/usr/bin/env python2
from __future__ import absolute_import # removing this line dosn't change anything. It's default functionality in python2.7 I guess
import numpy as np
It's fine when I execute test1.py
inside the test/
folder. But when I move to the top-dir/
the import numpy
wants to include my own util
package:
Traceback (most recent call last):
File "tests/laplace_2d_square.py", line 4, in <module>
import numpy as np
File "/usr/lib/python2.7/site-packages/numpy/__init__.py", line 137, in <module>
import add_newdocs
File "/usr/lib/python2.7/site-packages/numpy/add_newdocs.py", line 9, in <module>
from numpy.lib import add_newdoc
File "/usr/lib/python2.7/site-packages/numpy/lib/__init__.py", line 4, in <module>
from type_check import *
File "/usr/lib/python2.7/site-packages/numpy/lib/type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "/usr/lib/python2.7/site-packages/numpy/core/__init__.py", line 45, in <module>
from numpy.testing import Tester
File "/usr/lib/python2.7/site-packages/numpy/testing/__init__.py", line 8, in <module>
from unittest import TestCase
File "/usr/lib/python2.7/unittest/__init__.py", line 58, in <module>
from .result import TestResult
File "/usr/lib/python2.7/unittest/result.py", line 9, in <module>
from . import util
File "/usr/lib/python2.7/unittest/util.py", line 2, in <module>
from collections import namedtuple, OrderedDict
File "/usr/lib/python2.7/collections.py", line 9, in <module>
from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name itemgetter
The troublesome line is either
from . import util
or perhaps
from operator import itemgetter as _itemgetter, eq as _eq
What can I do?
Upvotes: 1
Views: 417
Reputation: 18187
operator is a module within the Python standard library. Giving a module of yours the same name as a standard module calls for trouble, and should be avoided.
If you absolutely need a way to get around this, you could try playing with the sys.path
variable. The first element is usually the directory of the script, or the empty string which directs the import system to the current directory.
oldpath = sys.path.pop(0)
import numpy
sys.path.insert(0, oldpath)
Upvotes: 1