Why "from . import re" fails but "import re; from . import re" succeeds?

Question:

I’m playing with Python’s relative import and the following result (with Python 3.7.3 on Debian 10.12) surprises me:

$ python3
>>> from . import re
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 're' from '__main__' (unknown location)
>>> import re
>>> re
<module 're' from '/usr/lib/python3.7/re.py'>
>>> from . import re
>>> re
<module 're' from '/usr/lib/python3.7/re.py'>
>>>

Why from . import re succeeds after import re? What’s happening?


UPDATE:

Python 3.8.2 on macOS 13.2 gives different result. Maybe a Python 3.7 bug?

>>> from . import re
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: attempted relative import with no known parent package
>>> import re
>>> re
<module 're' from '/Library/Developer/CommandLineTools/Library/Frameworks/
                   Python3.framework/Versions/3.8/lib/python3.8/re.py'>
>>> from . import re
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: attempted relative import with no known parent package
>>> re
<module 're' from '/Library/Developer/CommandLineTools/Library/Frameworks/
                   Python3.framework/Versions/3.8/lib/python3.8/re.py'>
>>>
Asked By: pynexj

||

Answers:

Yeah, a bug.

Going to the python changelog, for version 3.8.0 you can see the following:

bpo-37409: Ensure explicit relative imports from interactive sessions and scripts (having no parent package) always raise ImportError, rather than treating the current module as the package. Patch by Ben Lewis.

So if you don’t want that, make sure to use a python with version greater than 3.8.0

Answered By: Lærne
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.