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

Ian Kelly ian.g.kelly at gmail.com
Fri Sep 8 23:25:20 EDT 2017


On Fri, Sep 8, 2017 at 3:54 PM, Leam Hall <leamhall at gmail.com> wrote:
> On 09/08/2017 05:41 PM, Ian Kelly wrote:
>
>> 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.
>
>
>> 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?
>
>
> The path is not in the modules path or in sys.path. Hence the append. I
> thought I could add the local "lib" path via "." or "lib.", but it seems
> not.
>
> import lib.character fails in the tests/ directory.

Certainly not "lib.". The paths in sys.path need to be valid
filesystem paths for your OS. However, "." works for me:

(xenial)ikelly at localhost:~$ mkdir lib
(xenial)ikelly at localhost:~$ touch lib/__init__.py
(xenial)ikelly at localhost:~$ touch lib/character.py
(xenial)ikelly at localhost:~$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import lib.character
>>>
(xenial)ikelly at localhost:~$ mkdir tests
(xenial)ikelly at localhost:~$ echo "import lib.character" >
tests/test_character.py
(xenial)ikelly at localhost:~$ python3 tests/test_character.py
Traceback (most recent call last):
  File "tests/test_character.py", line 1, in <module>
    import lib.character
ImportError: No module named 'lib'
(xenial)ikelly at localhost:~$ export PYTHONPATH=.
(xenial)ikelly at localhost:~$ python3 tests/test_character.py
(xenial)ikelly at localhost:~$

The only thing I can think of is to question what the CWD is when
you're running the test. If it's not the parent directory of lib, then
of course "." wouldn't work.

Note from the transcript that when running interactively, '' (which is
equivalent to '.') is automatically prepended to sys.path, whereas
when running a script, the absolute path of the directory containing
the script is prepended instead. That's why PYTHONPATH needed to be
set for the second test but not the first.



More information about the Python-list mailing list