5 ms·
Sounds like a good idea. Not really a fan of the suggested syntax, though: def fn(s, n=>len(s)): "=>" just kind of bugs me, for some reason. (I love me some
by meowface 5y ago
Sounds like a good idea. Not really a fan of the suggested syntax, though:
def fn(s, n=>len(s)):
"=>" just kind of bugs me, for some reason. (I love me some bikeshedding.)
Of the alternatives they offer, ":=" kind of looks nicest to me:
def fn(s, n:=len(s)):
Though it doesn't really line up with the semantics of the existing walrus operator. Also, as the PEP mentions, it could look confusing when mixed with type annotations.
Semantically, the "?=" alternative might be best, since it kind of makes it clear it's a default, and doesn't conflict with anything else in the language:
def fn(s, n?=len(s)):
Kind of reads like "present? else = ...".
edit: At this point I'd shift from "might be best" to "almost certainly is best". I'm now a zealous "?=" advocate.
- kortex 5y agoI agree. I think python needs some solution to the `def foo(mylist=[])` which is a mistake I see devs make all the time. `foo=>func(a)` is awful. There's too much precedent that `x = f => {}` defines a lambda with x as a parameter. This flips it on its head. `@` would be challenging for the parser. `:=` also does not match the walrus semantics. `x ?= default` is perfect IMHO. There's already prior art (Makefiles) that this means exactly "present? else = ..." with lazy evaluation of RHS expression. It also would allow eliminating the "if x is SENTINEL" pattern, where None is a valid non-default argument.
- meowface 5y agoYeah, the more I look at it, the more I'm a fan of "?=". Kind of seems like the obvious choice at this point. The only potential downside is that standard, function definition-time default arguments also imply "present? else = ...". But I think of all the options available, this one makes the most sense.
- klyrs 5y agoHaving mylist stick around is actually useful for making stateful functions. For example, I've often used def foo(..., cache={}): ... to implement cached functions, or functions which need an internal cache for whatever reason. Later versions of Python provide an lru cache decorator, but that doesn't help with the internal cache and can be inefficient when you don't want your cache to forget any results.
- throwaway775888 5y agoWhat about .&= for default arguments?, inspired by Ruby.
- softwaredoug 5y agoI don't think its bike shedding FWIW, Python traditionally eschews fewer keywords and more obvious operators. So it's a reasonable concern.
- meowface 5y agoYeah, it's probably not bikeshedding when it concerns a very popular programming language's syntax. I just find myself prone to bikeshedding and pedantic naming indecisiveness in general.