bpo-32946: Speed up "from ... import ..." from non-packages.#5873
Conversation
| _handle_fromlist(module, module.__all__, import_, | ||
| recursive=True) | ||
| elif not hasattr(module, x): | ||
| from_name = '{}.{}'.format(module.__name__, x) |
There was a problem hiding this comment.
The attempt to import missing names as submodules should still be restricted to modules with a __path__ attribute. Something like try_import = hasattr(module, "__path__") before the loop, and then modify the condition on this branch to elif try_import and not hasattr(module, x):
There was a problem hiding this comment.
(Since we know at the point of calling whether module is a package or not, try_import could also be a parameter that defaults to False, with __import__ setting it to True as part of the call)
There was a problem hiding this comment.
The point of this issue is that this check is moved out from this function to calling places.
There was a problem hiding this comment.
In the issue for improving the error message for non-str objects in regular modules, calling this is one of the options for handling the enhancement. However, we only want to allow the first two branches for that use case, not the nested import one.
There was a problem hiding this comment.
Yes, I suggested this. But it would prevent the optimization made by this PR.
ncoghlan
left a comment
There was a problem hiding this comment.
+1 from me - we can consider the consequences for error reporting enhancements as part of https://bugs.python.org/issue32932
https://bugs.python.org/issue32946