Allow for globals and locals to be passed in as keyword arguments to exec and eval.
Pitch
exec and eval both can take globals and locals as positional arguments.
The built-in functions documentation shows the argument defaults, and every time I have the documentation open and am writing these, I default to keyword arguments, and it fails because the arguments are positional-only.
For functions like this that might only be present in a handful of places, kwargs give a good way to document what parameters each argument is referring to. I don't think that in a universe in which we were introducing eval/exec now that we would explicitly disallow kwargs.
Here is an implementation, which just consists in changing the argument clinic config and rerunning. I set up some very basic kwarg tests mostly to test the case of "locals provided but globals not provided", but fortunately the existing implementations already handled this cleanly!
@sunmy2019 I added a link to a commit implementing this. The short version is eval now has a bit more parsing code, but exec already has support for one kwarg, so we're still looking at the same order of magnitude of instructions or existing code IMO.
Activity
sunmy2019 commented on Jun 17, 2023
My concern is, will this hurt performance a lot?
JelleZijlstra commented on Jun 17, 2023
We can benchmark it, but that seems unlikely; parsing code is probably a lot slower than accepting some keyword arguments.
rtpg commented on Jun 17, 2023
@sunmy2019 I added a link to a commit implementing this. The short version is eval now has a bit more parsing code, but exec already has support for one kwarg, so we're still looking at the same order of magnitude of instructions or existing code IMO.
JelleZijlstra commented on Jun 17, 2023
Make a PR :)
rtpg commented on Jun 19, 2023
Created the PR, and tests seem to be passing now
gh-105879: Add support for keyword arguments to eval and exec (#105885)
JelleZijlstra commented on May 2, 2024
This will be in Python 3.13, thank you!
pythongh-105879: Add support for keyword arguments to eval and exec (p…
GH-105879: Note exec/eval keyword change in What's New (GH-121831)
pythonGH-105879: Note exec/eval keyword change in What's New (pythonG…
[3.13] GH-105879: Note exec/eval keyword change in What's New (GH-121831
pythonGH-105879: Note exec/eval keyword change in What's New (pythonG…
Add support for keyword arguments to eval and exec (python#105879)