Skip to content

Commit 72b5a55

Browse files
authored
Add comment to subtle dataclass code (gh-96133)
In the PR that made this change, 1st1 left a "note to self: add a comment explaining this". This comment was never added. https://github.com/python/cpython/pull/9518/files#r280608117 I was reading this code and it wasn't obvious to me why we weren't exec-ing directly into locals. So I got to learn something new :-) https://docs.python.org/3/reference/executionmodel.html#interaction-with-dynamic-features
1 parent 9e8b86d commit 72b5a55

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

Lib/dataclasses.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,10 @@ def _create_fn(name, args, body, *, globals=None, locals=None,
429429
# Compute the text of the entire function.
430430
txt = f' def {name}({args}){return_annotation}:\n{body}'
431431

432+
# Free variables in exec are resolved in the global namespace.
433+
# The global namespace we have is user-provided, so we can't modify it for
434+
# our purposes. So we put the things we need into locals and introduce a
435+
# scope to allow the function we're creating to close over them.
432436
local_vars = ', '.join(locals.keys())
433437
txt = f"def __create_fn__({local_vars}):\n{txt}\n return {name}"
434438
ns = {}

0 commit comments

Comments
 (0)