Regression: __import__ does not allow unicode strings in fromlist

Issue #2524 resolved
Eli Oxman created an issue

On regular Python 2.7 I see the following behavior:

>>> main_module = __import__('foo', fromlist=[u'bar'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named foo

On Pypy 5.6 I got the same behavior, but on Pypy 5.7 I get:

>>>> main_module = __import__('foo', fromlist=[u'bar'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'fromlist' items must be str, not unicode

I believe it should be possible to import with unicode literals in the fromlist. In particular I stumbled upon this when using a 3rd party library that uses from __future__ import unicode_literals.

Comments (8)

  1. mattip

    I see no difference when importing using the from __future__ import unicode_literals. I did fix the exception thrown in the case you described from a TypeError to an ImportError, but for me any use of unicode fails::

    mkdir A
    touch A/__init__.py
    touch A/B.py
    touch A/C.py
    python -c 'a = __import__("A", fromlist=["B"]); print dir(a)' # yeilds ['B', '__builtins__', ...
    python -c 'a = __import__("A", fromlist=[u"B"]);' # raises TypeError
    python -c 'from __future__ import unicode_literals; a = __import__("A", fromlist=[u"B"]);' # raises TypeError
    

    Note the last line does not succeed on python 2.7.12

  2. Eli Oxman reporter

    @mattip thanks for the quick response and feedback. I'm afraid that because my repro wasn't accurate enough I've led you to focus on the error message, while in reality I meant something else.

    The following should make it clearer:

    a = __import__('collections', fromlist=[u'defaultdict'])
    

    This statement works on Python 2.7 as well as on Pypy 5.6, but doesn't work on Pypy 5.7. At least on Python 2.7 I saw that the reason is that collections is a module (not a package), and so doesn't have the __path__ attribute, which is something that is checked in the CPython code when looking at the fromlist (and so makes it ignore whether it's unicode or not).

    In fact, even something like this works:

    d = __import__('collections', fromlist=1)
    

    The fromlist is completely ignored when importing from a module and not from a package.

  3. Log in to comment