3

I have read many previously asked questions about absolute and relative imports but I still cannot figure out how to solve the issue I have.

All my code is in the same directory contrary to some previously answered questions. I have added an empty __init__.py as suggested in some answers but it also does not change my issue.

My app structure:

cli/
    tests/
        __init__.py (empty)
        base.py
        util.py
        main.py

In base.py, doing from util import magical_function works (I can run my tests) but Pylint complains:

************* Module tests.base
W: 33, 0: Relative import 'util', should be 'tests.util' (relative-import)

I am running my tests using this script:

#!/usr/bin/env bash

CURRDIR="$(cd "$(dirname "$0")" && pwd)"

export PYTHONPATH=${CURRDIR}/../

source ${CURRDIR}/../activate
python ${CURRDIR}/../tests/main.py "$@"

activate starts the virtual environment:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

source ${DIR}/.virtualenv/bin/activate
source ${DIR}/.virtualenv/bin/postactivate

Following the instructions and having from tests.util import magical_function results in an error when running the tests: ImportError: No module named util.

How to change my import to have a working Python code and no errors found by Pylint (without disabling one of its checks)?

Community
  • 1
  • 1
Armand Grillet
  • 3,229
  • 5
  • 30
  • 60
  • @wim It seems the OP has clearly stated that his question slightly differs from the one you identified as a dupe. Care to explain why he was wrong? – Till Apr 25 '17 at 14:58
  • 1
    I've reopened it. The problem is the same cause, but best practice here would probably be to add a `setup.py` and install the package in development mode, before executing the test suite. I'm unable to find a good duplicate about that, there are many questions on the topic but they are mostly full of crap answers and bad advice :-\ – wim Apr 25 '17 at 15:23
  • Armand should add details of how the test runner is invoked, and where the library code lives. – wim Apr 25 '17 at 15:25
  • @wim After further testing, the issue is due to the virtual environment (sorry I did not mention that in my initial question). I have added the two scripts used when running the tests. – Armand Grillet Apr 25 '17 at 15:48
  • That's somewhat messy way to run the tests. It is also relevant which directory the script lives in, and from which directory you execute that script. What is the point of `tests/main.py`? Why not just use a proper test runner such as nose or pytest? – wim Apr 25 '17 at 16:50

0 Answers0