On Fri, Dec 03, 2021 at 10:40:42AM +1100, Chris Angelico wrote:
Here's what you get:
def f(lst=>[], n=>len(lst)): ... ... f.__defaults_extra__ ('[]', 'len(lst)')
String representation, but exactly what the default is.
Excellent. And you've just proven that we can evaluate the defaults. >>> a = '[]' # f.__defaults_extra__[0] >>> b = 'len(lst)' # f.__defaults_extra__[1] >>> lst = eval(a, globals()) >>> n = eval(b, globals(), dict(lst=lst)) >>> print(lst, n) [] 0 Worst case scenario, we can eval the string representation, and that should work for the great majority of cases that don't involve nonlocals. But if the defaults are proper code objects, complete with a closure to capture their nonlocal environment, then we should be able to do even better and capture nonlocals as well. Could there be odd corner cases that don't quite work? Say, like a comprehension inside a class body? https://github.com/satwikkansal/wtfpython#-name-resolution-ignoring-class-sc... Oh well. Let's not make the perfect the enemy of the good. -- Steve