[Python-ideas] Disallow importing the same module under multiple names

Chris Billington chrisjbillington at gmail.com
Wed Mar 14 01:20:20 EDT 2018


The Python "double import" problem (discussed here
<http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html>)
leads to subtle bugs in code that change depending on what directory the
code was run from.

It's hard to think of reasons why importing the same filepath multiple
times resulting in two copies of a module should be allowed, it almost
always indicates a mistake in code. One possible solution I though of is to
return the existing module upon import under a different name. Then you
would still have two names for the same module, but at least it would be
the same module object, not two copies of it loaded separately from the
same file. However, then you would have the situation where a modules
__name__ attribute would not match at least one of the names it was
imported as.

Instead, maybe a user should just get a big fat error if they try to import
the same file twice under different names.

For frozen modules, and other fancy imports, users should be able to do
what they like, but for ordinary file-based imports, it's easy enough to
detect if a module has been imported under two different names (by
inspecting the filepath of the module being loaded and seeing if that
filepath has previously been loaded under a different name) and throw an
exception.

I've recently made an addition to a project of mine
<https://bitbucket.org/labscript_suite/labscript_utils/src/default/double_import_denier.py>
 to turn this type of detection on all the time so that we don't miss these
subtle bugs (we encountered some whilst porting to Python 3 since we
started using absolute imports).

I wonder if there's any reason something like this shouldn't be built into
Python's default import system.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180314/f98cf454/attachment.html>


More information about the Python-ideas mailing list