Last Updated: January 28, 2019
·
1.226K
· oleiade

Python : container destructuration pattern snippet

One of the functional programmation pattern I enjoy and use the most is sequence container destructuration: when you use pattern matching, for example. (Haskell uses the [x:xs] syntaxic sugar).

Destructuration is just a fancy name for slicing a list.

Most of the time you use it to get the head of your list, and the rest of it appart. And I found it lacking in python (correct me if I'm wrong) when I was trying to do such things :

commands = ([signal, key, value], ...)
for command in commands:
    signal, args = **destructuring command**

Of course I could have used two lines like this :

signal = command.pop(0)
args = command

But it sounded important to me to be able to do it in one line, and without altering the original container. So here's my snippet for destructuration :

from collections import Sequence

def destructurate(container):
    class DestructurationError(Exception):
        pass

    if isinstance(container, Sequence):
        return container[0], container[1:]
    else:
        raise DestructurationError("Can't destructurate a non-sequence container")

That in my case you can use like :

>>> signal, args = destructurate(command)
>>> signal
signal
>>> args
[key, value]

1 Response
Add your response

If your only goal is to make it a one-liner, you can do signal, args = command.pop[0], command, or signal, args = command[0], command[1:].

over 1 year ago ·