Search code examples
pythonpytestwarnings

pytest hides warnings when __pycache__ is used


Pytest warnings are different between first and subsequent runs.

janbet@ub/home/janbet $ cat test_x.py 
def test_1():
    a = '\d'
janbet@ub/home/janbet $ pytest test_x.py | tail -1
========================= 1 passed, 1 warning in 0.00s =========================
janbet@ub/home/janbet $ pytest test_x.py | tail -1
============================== 1 passed in 0.00s ===============================

Warning appears again after rm -r __pycache__ or touch test_x.py or something like this.

I guess those warnings are created when .py files are read, and when __pycache__ is available and up-to-date they are not read at all. Is this correct?

Is there any simple way to force pytest never to use __pycache__ at all? This is probably not very important, but I have a strong aversion to situations when my test run result depends on some internal files created-or-not during previous runs.


Solution

  • for this particular warning, this is consistent with how python works -- invalid escape sequence warnings are only omitted when compiling the source (after that, pyc files are available and the source is not consulted)

    you can set the PYTHONDONTWRITEBYTECODE=1 environment variable to prevent pyc writing, but then you'll have to deal with the slow startup cost of compiling code repeatedly

    I'd recommend using a linter instead to detect this (flake8 for example detects this via pycodestyle in the default case) and/or an autofixer to fix this (pyupgrade for example fixes this)


    disclaimer: I'm a core dev of pytest, I'm the current maintainer of flake8, I'm a maintainer of pycodestyle, I created pyupgrade