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

47 Upvotes

30 comments sorted by

16

u/aes110 18h 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

6

u/JanEric1 18h 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.

27

u/HugeCannoli 19h ago

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

13

u/JanEric1 19h ago edited 18h 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

7

u/HommeMusical 18h 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.

8

u/def__eq__ 13h ago

I’ll probably be unpopular here, but “just because you can, doesn’t mean you should”.

This opens a Pandora’s box of debug issues and it will end up being used in really obscure ways. Not to mentioned that the simple alternative is to set the default value to None and then in the function decide what the default should be for that parameter. Where’s the issue?

0

u/JanEric1 13h ago

Don't see the debug issue to be honest.

And the issues with "that" are referenced in the pep. It complicates the code, gives a wrong signature and makes the "real" default harder to find.

Given that, I am still not sure if it is worth the more complicated signatures, teaching and edge cases.

3

u/def__eq__ 13h ago

When does any exception occur? When the function is executed or when it is referred to for its signature?

The extra line of “if var_A is None:” is anyways followed by the same default calculation and if it is declared right after the function declaration then it is not so hard to find.

I’ll check out the PEP, but so far I really don’t see it…

1

u/JanEric1 13h ago

What do you mean referred to for its signature? Exception triggers when the default expression is evaluated which would be every call of the function, because the whole point is that the expression runs in every call. It's basically just prepended to the body

1

u/def__eq__ 13h ago

That I understand, but what about all the other times the function is inspected for its signature? Would it also trigger then? What about Python tests that check whether default hasn’t changed?

What if the default calculation is not a one liner but another custom function? That really makes debugging and type checking a nuisance.

1

u/JanEric1 13h ago edited 12h ago

I think how signature inspection works is not 100% decided, there is some discussion in the discuss thread. I think in one case the current (WIP) implementation just skips them when you try to get the default values. I suspect you will be able to chose how you want to handle them. If you want to just get strong or evaluate them yourself, in which case they would run and trigger exceptions. Default would likely be that you get something that indicates that it is late bound where you would currently get the early bound default value.

Edit: Had a quick look at the current impl. Currently if you have a late bound arg you get a placeholder of Ellipsis (aka ...) and store the string in __default_extras__. And so most things just give you that back (at the moment). What is weird i would say is apply_defaults into the args of a signature, where the late bounds are just skipped.

def f(a, b=10, c=>a+b): ...

f.__defaults__ = (10, Ellipsis)
f.__default_extras__ = (None, 'a+b')
inspect.signature(f) = (a, b=10, c=>a+b)
inspect.getfullargspec(f) = FullArgSpec(args=['a', 'b', 'c'], varargs=None, varkw=None, defaults=(10, Ellipsis), kwonlyargs=[], kwonlydefaults=None, annotations={}, defaults_extra=(None, 'a + b'), kwonlydefaults_extra=None)
inspect.getcallargs(f, 1) = {'a': 1, 'b': 10, 'c': Ellipsis}
inspect.signature(f).bind(1) = <BoundArguments (a=1)>
inspect.signature(f).bind(1).arguments = {'a': 1}
bound_arguments = inspect.signature(f).bind(1)
bound_arguments.argument = {'a': 1, 'b': 10}
inspect.signature(f).parameters['b'].default = 10
inspect.signature(f).parameters['b'].extra = None
inspect.signature(f).parameters['c'].default = Ellipsis
inspect.signature(f).parameters['c'].extra = a + b

But i still dont see how this makes debugging and type checking a nuisance? Those two things arent affected at all? You obviously need changes to signature and default value inspecting, because you are making changes to default values in signatures...

If you call a custom function that function will be called to provide the default value whenever you call the function without providing a value for that parameter? Seems very straight forward to me tbh.

2

u/ohnoitssobig 13h ago

I do not think it will make it. You can implement a decorator and achieve the same behavior but more explicitly and with well-defined boundaries. Changes to typing, introspection are too intrusive. The "left-to-right" evaluation order has to be memorized and is a sort of an arbitrary choice.

1

u/JanEric1 13h ago

Can you show that decorator that you feel does this better?

And I feel left to right is simply the natural choice and what 99% of people will just assume?

3

u/ohnoitssobig 13h ago

I assumed that it will build a full dependency graph and descend through it. A decorator would be something like this

@eval_args
def bisect_right(a, x, lo=0, hi=delayed_eval(lambda a: len(a)), *, key=None):

1

u/JanEric1 13h ago

Missing the definition of the decorator here?

And here you need way more than just a decorator, you need that lambda + (optionally?) that wrapper for it.

=> is significantly simpler and more readable.

2

u/ohnoitssobig 12h ago

The definition of the decorator is not important here because whatever it is, PEP implementation will have to do the same. It will inspect the function, figure out what arguments it has and what needs to be evaluated, and will create a wrapper to do that. PEP implementation introduces new opcodes but I doubt requiring new opcodes has any chance to go through at all so it will probably be simplified (or complicated?) to some sort of a built-in decorator.

I am not saying that the decorator approach is a pinnacle of code style but it is readable, explicit, and it is ok for what it does. Either way, this change does not come for free and has to be considered together with the burden required to implement and support it. It needs a lot of work from the core python team (which will resist new opcodes) but also those working on typing, linters, IDEs. It may and will backfire in various packages doing introspection such as cython.

2

u/JanEric1 12h ago

but I doubt requiring new opcodes has any chance to go through

Why? opcodes are changed all the time? Like every version changes them i think.

And the current impl just stores a placeholder in __default__ and provides the string as a marker in __default_extras__. Then places a function proloig before the normal bytecode that for each of the late bounds checks if they were supplied and if so skips the code that evalutes the expression and assigns it.

Of course it will require maintanence in cpython... just like all the other features that are added there, same with linters and type checkers. But probably mountains less than lazy imports for example.

SPecifically type checkers should have absolutely zero issue with this and i dont think linters will care much either?

2

u/ohnoitssobig 12h ago

To sum up, considering the implementation and support burden, I do not think it will make it.

1

u/JanEric1 1h ago

I also dont think it will make it, but i dont think impl and support will play ANY role in that.

15

u/knobbyknee 11h ago

I'm against this change. It would add yet another complexity to the language to support a very niche use case.

It becomes something that everyone has to learn, like all language features, because when you encounter it in someone elses code, you need to understand it.

There are many such burdens in Python these days. Some of them are small, like the walrus operator and some of them are large like async, full understanding of multi-level generators.

3

u/SuspiciousScript 9h ago

It becomes something that everyone has to learn, like all language features, because when you encounter it in someone elses code, you need to understand it.

This is no less true of the existing mutable default argument behaviour.

5

u/knobbyknee 9h ago

It is a wart in the definition of Python, and it won't go away when you add another one.

8

u/Individual-Flow9158 17h ago

Feels like a code smell to me.

4

u/Chroiche 17h ago

Shared instance for defaults is one of my least favourite things about Python so I welcome it. I'd probably never use the "old" way by choice if this got released as suggested.

2

u/logophage 13h ago

Late binding would definitely be useful and not just for types but also, say, by calling a init fn. I found it useful enough I wrote a set of decorators that lets me do late binding. But having in language would be better.

That said, I don't like => only because it's a new form introduced into the language. Someone here suggested := which kinda works. I'd be inclined to use that.

3

u/baubleglue 13h ago

it used to be a simple language

2

u/RevolutionaryFunny40 19h 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.

6

u/backfire10z 16h ago

This doesn’t remove the default argument trap, it just changes how you deal with it. You still have to remember to do this.

•

u/OhYourFuckingGod 52m ago

Python's going to end up as a tremendously slow C++ if we keep adding syntax variations every version.