Re:Upcoming Python features brought to you by Python Enhance...
by eloisius on Monday February 14, 2022 @09:54AM
(#30332675)
So it’s not specific to functions as arguments? A long-time gripe I’ve had about default parameters in Python is that they are static from function definition time instead of dynamic at call time. A consequence of that is that if you have a function like
def foo(bar, baz=[]):
baz.append(bar)
return baz
baz will be reused for the duration of the process kind of like a global variable.If this new syntax fixes that, I see the value.
Re:Upcoming Python features brought to you by Python Enhance...
by Sohcahtoa82 on Monday February 14, 2022 @03:51PM
(#30338118)
> If this new syntax fixes that, I see the value.
It does. The old syntax creates and assigns the variable at compile-time. => does it at execution time.
So this code:
def foo(bar, baz=[]):
baz.append(bar)
return baz
foo(1)
foo(2)
print(foo(3))
would print '[1, 2, 3]'But this code:
def foo(bar, baz=>[]):
baz.append(bar)
return baz
foo(1)
foo(2)
print(foo(3))
would print '[3]'
>Function parameters can have default values which are calculated during function definition and saved. This proposal introduces a new form of argument default, defined by an expression to be evaluated at function call time