pytest cannot import module while python can pytest cannot import module while python can python python

pytest cannot import module while python can


Found the answer:

DO NOT put a __init__.py file in a folder containing TESTS if you plan on using pytest. I had one such file, deleting it solved the problem.

This was actually buried in the comments to the second answer of PATH issue with pytest 'ImportError: No module named YadaYadaYada' so I did not see it, hope it gets more visibility here.


I can't say I understand why this works, but I had the same problem and the tests work fine if I run python -m pytest.

I'm in a virtualenv, with pytest also available globally:

(proj)tom@neon ~/dev/proj$ type -a pythonpython is /home/tom/.virtualenvs/proj/bin/pythonpython is /usr/bin/python(proj)tom@neon ~/dev/proj$ python -VPython 3.5.2(proj)tom@neon ~/dev/proj$ type -a pytestpytest is /home/tom/.virtualenvs/proj/bin/pytestpytest is /usr/bin/pytest(proj)tom@neon ~/dev/proj$ pytest --versionThis is pytest version 3.5.0, imported from /home/tom/.virtualenvs/proj/lib/python3.5/site-packages/pytest.py


I just solved this by removing the __init__.py in my project root:

.├── __init__.py <--- removed├── models│   ├── __init__.py│   ├── address.py│   ├── appointment.py│   └── client.py├── requirements.txt├── setup.cfg├── tests│   ├── __init__.py│   ├── models│   │   ├── __init__.py│   │   ├── appointment_test.py│   │   └── client_test.py│   └── other_test.py└── script.py