Feature or enhancement
Proposal:
Currently, every time annotationlib runs a function in a fake globals namespace, it builds a closure with _build_closure(). This function iterates over the closure variables in func.__closure__ and names them in __code__.co_freevars, defaulting to "cell" if the variable is unnamed:
|
if i < len(freevars): |
|
name = freevars[i] |
|
else: |
|
name = "__cell__" |
This default process is fine, but as far as I can tell, it is unnecessary and cannot be tested (as in #141174)
A function's __closure__ attribute is read-only, and is always generated with the same length as __code__.co_freevars by the compiler. __code__ itself is writable, but can only be set to a code object, which cannot be subclassed. Furthermore, when assigning a function's __code__ attribute, its co_freevars is enforced as being the same length as the __closure__.
A non-function could be passed as an 'annotate function' with custom __code__ and __closure__ attributes - except when the function is run in a fake globals namespace, it is re-created through the types.FunctionType constructor, which enforces its __code__ being an actual code object.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Linked PRs
Feature or enhancement
Proposal:
Currently, every time
annotationlibruns a function in a fake globals namespace, it builds a closure with_build_closure(). This function iterates over the closure variables infunc.__closure__and names them in__code__.co_freevars, defaulting to "cell" if the variable is unnamed:cpython/Lib/annotationlib.py
Lines 842 to 845 in 781cc68
This default process is fine, but as far as I can tell, it is unnecessary and cannot be tested (as in #141174)
A function's
__closure__attribute is read-only, and is always generated with the same length as__code__.co_freevarsby the compiler.__code__itself is writable, but can only be set to acodeobject, which cannot be subclassed. Furthermore, when assigning a function's__code__attribute, itsco_freevarsis enforced as being the same length as the__closure__.A non-function could be passed as an 'annotate function' with custom
__code__and__closure__attributes - except when the function is run in a fake globals namespace, it is re-created through thetypes.FunctionTypeconstructor, which enforces its__code__being an actual code object.Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Linked PRs
annotationlib._build_closure()#141490annotationlib._build_closure()(GH-141490) #141776