r/Python • • 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

21 Upvotes

6 comments sorted by

11

u/HugeCannoli 1h ago

why not the walrus, it's the perfect choice for this behavior.

5

u/JanEric1 1h ago edited 39m ago

Because the colon already has a use in function signature and you can use it in the default expression are I think the main considerations. Guide proposed ??= matching the recently accepted null coalescing PEP (which accepted ?? but actually rejected ??= for the moment)

def foo(var: list := [])
def bar(a: list, var: list := (a := []))  # DONT DO THIS

vs

def foo(var: list => [])
def bar(a: list, var: list => (a := []))  # STILL DONT DO THIS

•

u/HommeMusical 41m ago

In the discussion linked, the proposer points out that : already appears in parameters introducing the type annotations so using : for a different purpose in the same tiny area makes it harder for both people and computers to read.

•

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.

  1. 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 error

    def foo(a=>b, b=2): print(a, b)

    foo() # 2, 2 foo(b=5) # 5, 5 foo(a=2, b=3) # 2, 3

  2. In my version you can explicitely pass None to 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.