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

Issue #371 wontfix
Chiu Hsiang Hsu created an issue

how to trigger this bug :

└── xml

in, I only put :

from xml import package

other files are empty can run happily with CPython :

$ python

but it will failed with coverage

$ coverage run
Traceback (most recent call last):
  File "", 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 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 "" 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