diff options
author | Jelle Zijlstra <jelle.zijlstra@gmail.com> | 2024-07-27 10:24:10 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-07-27 17:24:10 +0000 |
commit | ae192262ad1cffb6ece9d16e67804386c382be0c (patch) | |
tree | 301564405a80de59fd6b04e508166a759ff434d0 /Lib/annotationlib.py | |
parent | cbac8a3888411587beb026e246889154fbdd49a3 (diff) | |
download | cpython-ae192262ad1cffb6ece9d16e67804386c382be0c.tar.gz cpython-ae192262ad1cffb6ece9d16e67804386c382be0c.zip |
gh-119180: Add evaluate functions for type params and type aliases (#122212)
Diffstat (limited to 'Lib/annotationlib.py')
-rw-r--r-- | Lib/annotationlib.py | 19 |
1 files changed, 16 insertions, 3 deletions
diff --git a/Lib/annotationlib.py b/Lib/annotationlib.py index eea24232f9f..141e31bbf91 100644 --- a/Lib/annotationlib.py +++ b/Lib/annotationlib.py @@ -413,7 +413,16 @@ class _StringifierDict(dict): return fwdref -def call_annotate_function(annotate, format, owner=None): +def call_evaluate_function(evaluate, format, *, owner=None): + """Call an evaluate function. Evaluate functions are normally generated for + the value of type aliases and the bounds, constraints, and defaults of + type parameter objects. + """ + return call_annotate_function(evaluate, format, owner=owner, _is_evaluate=True) + + +def call_annotate_function(annotate, format, *, owner=None, + _is_evaluate=False): """Call an __annotate__ function. __annotate__ functions are normally generated by the compiler to defer the evaluation of annotations. They can be called with any of the format arguments in the Format enum, but @@ -459,8 +468,11 @@ def call_annotate_function(annotate, format, owner=None): closure = tuple(new_closure) else: closure = None - func = types.FunctionType(annotate.__code__, globals, closure=closure) + func = types.FunctionType(annotate.__code__, globals, closure=closure, + argdefs=annotate.__defaults__, kwdefaults=annotate.__kwdefaults__) annos = func(Format.VALUE) + if _is_evaluate: + return annos if isinstance(annos, str) else repr(annos) return { key: val if isinstance(val, str) else repr(val) for key, val in annos.items() @@ -511,7 +523,8 @@ def call_annotate_function(annotate, format, owner=None): closure = tuple(new_closure) else: closure = None - func = types.FunctionType(annotate.__code__, globals, closure=closure) + func = types.FunctionType(annotate.__code__, globals, closure=closure, + argdefs=annotate.__defaults__, kwdefaults=annotate.__kwdefaults__) result = func(Format.VALUE) for obj in globals.stringifiers: obj.__class__ = ForwardRef |