This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: __import__ doesn't honour globals
Type: enhancement Stage:
Components: Documentation Versions: Python 3.6
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: brett.cannon, docs@python, serhiy.storchaka, stefan
Priority: normal Keywords:

Created on 2020-04-10 22:33 by stefan, last changed 2022-04-11 14:59 by admin.

Messages (6)
msg366160 - (view) Author: Stefan Seefeld (stefan) * (Python committer) Date: 2020-04-10 22:33
I'm trying to import custom scripts that expect the presence of certain variables in the global namespace.
It seems `__import__('script', globals=dict(foo='bar'))` doesn't have the expected effect of injecting "foo" into the namespace and making it accessible to the script being loaded.

Is this a bug in `__import__` or am I missing something ? If the behaviour is expected, how can I achieve the desired behaviour ?
msg366161 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2020-04-10 22:50
globals is only used when level > 0, to resolve relative names like in `import`. You have to set keys __package__ and __spec__ or __name__ and __path__ in this case.
msg366181 - (view) Author: Stefan Seefeld (stefan) * (Python committer) Date: 2020-04-11 02:22
OK, thanks for the clarification. I think this is obscure enough to warrant at least a paragraph or two to clarify the semantics of these arguments.
I changed the issue "components" and "type" to reflect that.
msg366435 - (view) Author: Brett Cannon (brett.cannon) * (Python committer) Date: 2020-04-14 19:39
How would you propose changing the wording found at
msg366438 - (view) Author: Stefan Seefeld (stefan) * (Python committer) Date: 2020-04-14 19:53
I'm not entirely sure, but have to admit that the sentence

"The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context."

is a bit obscure. What does "determine how to interpret the name" actually mean ? Is the algorithm described anywhere in detail ? In that case, a simple reference might be enough.
msg366530 - (view) Author: Brett Cannon (brett.cannon) * (Python committer) Date: 2020-04-15 17:08
Algorithm is documented as part of the language reference:
Date User Action Args
2022-04-11 14:59:29adminsetgithub: 84430
2020-04-15 17:08:34brett.cannonsetmessages: + msg366530
2020-04-14 19:53:52stefansetmessages: + msg366438
2020-04-14 19:39:37brett.cannonsetnosy: + brett.cannon
messages: + msg366435
2020-04-11 02:22:06stefansetnosy: + docs@python
messages: + msg366181

assignee: docs@python
components: + Documentation, - Interpreter Core
type: behavior -> enhancement
2020-04-10 22:50:25serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg366161
2020-04-10 22:33:48stefancreate