[Python-ideas] Allow popping of slices

Ben Rudiak-Gould benrudiak at gmail.com
Mon Jun 4 18:23:07 EDT 2018

The `pop` method of built-in sequences is basically an atomic version of

    val = self[pos]
    del self[pos]
    return val

If this behavior was extended to the case where `pos` is a slice, you
could write things like:

    def cut_deck(deck, pos):
        deck.extend(deck.pop(slice(0, pos)))

    def bfs(roots):
        depth, frontier = 0, list(roots)
        while frontier:
            depth += 1
            for item in frontier.pop(slice(None)):

Similar functionality is found in many other languages (e.g. Perl and
JavaScript's `splice`). I think it's useful not just because it's more
concise, but because it's linear/reversible: it moves data rather than
duplicating and then destroying it, which makes it less prone to bugs.

The syntax is a bit odd since you have to construct the slice by hand.
Here are three solutions for that from least to most extravagant:

 1. Don't worry about it. It's still useful, and the syntax, though
verbose, makes sense. (The "reference implementation" of pop is
literally unchanged.)

 2. Give pop methods a __getitem__ that does the same thing as
__call__, so you can write xs.pop[-1] or xs.pop[:].

 3. Promote del statements to expressions that return the same values
as the underlying __delitem__, __delattr__, etc., and make those
methods of built-in types return the thing that was deleted. (Or
introduce __popitem__, __popattr__, etc. which return a value.)

-- Ben

More information about the Python-ideas mailing list