[Python-ideas] Add "default" kwarg to list.pop()

Steven D'Aprano steve at pearwood.info
Fri Nov 2 06:59:15 EDT 2018


On Fri, Nov 02, 2018 at 10:48:22AM +0200, Serhiy Storchaka wrote:
> 31.10.18 21:23, Robert Vanden Eynde пише:
> >Should I write a PEP even though I know it's going to be rejected 
> >because the mailing list was not really into it ?

I disagree that "the mailing list was not really into it".

So far, I count 12 people who responded to the original post by 
Giampaolo. By my count, I see:

* five people in favour;
* three people against, or see no need for it;
* four people I can't tell if they are for or against, 
  (possibly neutral?) [1]

I know that adding features isn't decided by majority vote, but it seems 
clear to me that there is a substantial set of Python users, perhaps a 
majority, who would find this feature useful and more obvious than the 
alternatives.


[Serhiy]
> It is better to not do this. PEP 572 was initially written with the 
> intention to be rejected.

Sounds like an excellent reason to write a PEP :-)

There are some issues that ought to be addressed:

- The status quo is easy to get wrong:

    # I've written this. More than once.
    L.pop(idx) if idx < len(L) else default

  is wrong if there is any chance of idx being negative.


- The more common case of popping from the front of the list
  is not thread-safe:

    L.pop() if L else default


- This clever trick is probably thread-safe (I think...) but it
  is wasteful and inefficient:

    (L or [default]).pop()

  and it isn't obvious how to adapt it efficiently if you need to 
  pop from an arbitrary index. I came up with this:

    (L[idx:idx+1] or [default]).pop()

  but it is doubly wrong.


- The obvious thread-safe EAFP idiom is a try...except statement, so 
  it needs to be wrapped in a helper function to use it in expressions.
  That adds more overhead.


The proposed .get(idx, default=x) and .pop(idx, default=x) signatures 
ought to be obvious and unsurprising to any moderately experienced 
Python programmer. These aren't complicated APIs.


On the other hand:

- I'm not volunteering to do the work (I don't know enough C to write
  a patch). Unless somebody has a patch, we can't expect the core devs
  who aren't interested in this feature to write it.

(Hence, status quo wins a stalemate.)






[1] "What makes a man turn neutral? Lust for gold? Power? Or were you 
just born with a heart full of neutrality?" -- Captain Zapp Brannigan


-- 
Steve


More information about the Python-ideas mailing list