import in coverage does not work the same way that CPython does

Issue #371 wontfix
wdv4758h
created an issue

how to trigger this bug :

.
├── test.py
└── xml
    ├── __init__.py
    └── package.py

in test.py, I only put :

from xml import package

other files are empty

test.py can run happily with CPython :

$ python test.py

but it will failed with coverage

$ coverage run test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from xml import package
ImportError: cannot import name package

I found that it's finding package in /usr/lib/python2.7/xml/ rather than ./xml

Any idea about this problem ?

test in version 4.0a6 and 3.7.1

Comments (2)

  1. Ned Batchelder repo owner

    This happens because coverage.py imports xml.dom.minidom when starting up, so "xml" is already in sys.modules.

    I'm not sure what can be done to fix it. The xml import could be moved into a function, since it's only used in one place, but that doesn't fix the problem in general. If you wanted to have your own "time.py" module shadow the stdlib time module, you'd have the same problem, and I can't see moving all those imports into the functions that use them.

    You can solve the problem in your code with this ugliness:

    if 'xml' in sys.modules:
        del sys.modules['xml']
    from xml import package
    

    but that gets unwieldy as you have xml imports in more than one place.

  2. Log in to comment