0

In python you can't define such a function :

def cutafter(aList, end=len(aList)-1):
    return aList[:end]

Because it says : NameError: name 'aList' is not defined

But you can easily défine:

def cutafter(aList, end=None)
    if not(end):
        end=len(aList)-1
    return aList[:end]

which is a very general trick. That's exactly what optionnal means to me.

So why is it not a feature ?

  • 1
    Default values are evaluated when the function is defined, not when it's called. So they can't depend on other parameters. – Barmar May 03 '23 at 21:45
  • See https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument . Tangential but totally related to how function arguments are evaluated – roganjosh May 03 '23 at 21:46
  • @Barmar hence why I didn't flag as a dupe. I just think it's a good starting point to understand the behaviour of function signatures in general – roganjosh May 03 '23 at 21:47
  • @roganjosh I can't seem to find a good dup. All my search results are either about `arg=[]` (which are all then linked to the "least astonishment" canonical dup) or `arg=variable` (where `variable` is a global variable that they modify after definition). – Barmar May 03 '23 at 21:49
  • @roganjosh Found it! – Barmar May 03 '23 at 21:50
  • And found another one that tries exactly the same `end=len(previousarg)-1` default as this one. – Barmar May 03 '23 at 21:51
  • This has been proposed in PEP 671: https://peps.python.org/pep-0671/. Note this example which is very similar to the one in your question: `def bisect_right(a, x, lo=0, hi=>len(a), *, key=None):` (The idea is that the `=>` operator would allow an argument to be evaluated in terms of other arguments.) – slothrop May 03 '23 at 21:53
  • So we're close to a feature ? – Poor Standard May 03 '23 at 22:11
  • Well. There's certainly a very long discussion about it... https://mail.python.org/archives/list/python-ideas@python.org/thread/UVOQEK7IRFSCBOH734T5GFJOEJXFCR6A/ – slothrop May 04 '23 at 08:24

0 Answers0