Not appending ("lib") to sys.path breaks tests.

Ian Kelly ian.g.kelly at gmail.com
Fri Sep 8 17:41:26 EDT 2017


On Fri, Sep 8, 2017 at 3:18 PM, Leam Hall <leamhall at gmail.com> wrote:
> A kind soul pointed out that my code uses a sys.path.append("lib") to get
> files to be imported:
>
>         sys.path.append("lib")
>         from character_tools import *
>
> He noted that having an __init__.py in lib and using:
>
>         from .character_tools import *
>
> Should be sufficient for "please don't comment yet about 'import *'" levels
> of sufficient.   :P

I'm confused about where the character_tools import is made. If that's
within a module in the lib package, it should be fine.

> The code works under python 2.6.6 and 3.6.2. However, py.test (python 2) and
> pytest (python 3) fails. Besides my usual clue, what am I missing?
>
>
>
> ### py.test (python 2)
> ========================================= test session starts
> =========================================
> platform linux2 -- Python 2.6.6 -- pytest-2.3.5
> collected 0 items / 3 errors
>
> =============================================== ERRORS
> ================================================
> ______________________________ ERROR collecting tests/test_base_tools.py
> ______________________________
> tests/test_base_tools.py:6: in <module>
>>   import lib.base_tools
> E   ImportError: No module named lib.base_tools

It looks like it's failing to find the lib package. Since you removed
the "lib" directory from sys.path, does its parent directory exist in
sys.path?


> ______________________________ ERROR collecting tests/test_character.py
> _______________________________
> /usr/lib/python2.6/site-packages/_pytest/python.py:352: in _importtestmodule
>>           mod = self.fspath.pyimport(ensuresyspath=True)
> /usr/lib/python2.6/site-packages/py/_path/local.py:621: in pyimport
>>           __import__(modname)
> E             File
> "/home/leam/lang/git/makhidkarun/py_tools/tests/test_character.py", line 6
> E               import .lib.character
> E                      ^
> E           SyntaxError: invalid syntax

Relative imports are only allowed with the "from .foo import bar" syntax.

However if you fix that, I suspect you're then going to run into the
next error below here. I think you actually just want an absolute
import like "import lib.character" here.


> ___________________________ ERROR collecting tests/test_character_tools.py
> ____________________________
> tests/test_character_tools.py:6: in <module>
>>   from ..lib.character_tools import *
> E   ValueError: Attempted relative import in non-package

Packages and directories are not the same thing. This is saying that
the tests directory is not a package, so you can't do a relative
import within it. You probably just want "from lib.character_tools
import *".

The Python 3 errors are the same as the above.



More information about the Python-list mailing list