r/Python • u/JanEric1 • 1h ago
Discussion PEP 671 – Syntax for late-bound function argument defaults
https://peps.python.org/pep-0671/
The PEP was originally proposed in October 2021 but didnt get much traction. Through some discussions on the python discuss the author picked it up again and reproposed it for 3.17
It proposes a new syntax argument => late_bound_default()
def add_item(item, target=>[]):
def bisect_right(a, x, lo=0, hi=>len(a), *, key=None):for late binding of argument defaults. This would allow avoiding the common mutable default argument trap and would allow for defaults to refer to previous arguments as seen in the biset_right example above.
Discussion can be found here: https://discuss.python.org/t/pep-671-syntax-for-late-bound-function-argument-defaults/110297
Note: I am not the PEP author
•
u/aes110 44m ago
I don't mind the mutable default example, but the bisect one doesn't sit right with me
Running all sort of expressions inside function arguments seems wrong, though i admit it looks kinda cool lol
•
u/JanEric1 35m ago
Its basically just moving each late bound arg into the body in order
def foo(a => funca(), b => funcb(a), c => funcc(a, b): ...is close to
def foo(a=None, b=None, c=None): if a is None: a = funca() if b is None: b = funcb(a) if c is None: c = funcc(a, b)There are some differnces though.
with the late bound you cant reference c from funca() (or more generally later latebound params, you CAN reference later early bounds) which you could in my example and always get
None, here you get an errordef foo(a=>b, b=2): print(a, b)
foo() # 2, 2 foo(b=5) # 5, 5 foo(a=2, b=3) # 2, 3
In my version you can explicitely pass
Noneto get the default value, with the=>you cant.
1
u/RevolutionaryFunny40 1h ago
oh nice i’ve always hated the “default” be logic in code because of the default argument trap
R has the same semantics as this, like it a lot.
11
u/HugeCannoli 1h ago
why not the walrus, it's the perfect choice for this behavior.