[Python-ideas] Dictionary destructing and unpacking.

C Anthony Risinger c at anthonyrisinger.com
Thu Jun 8 05:00:38 EDT 2017


On Jun 8, 2017 1:35 AM, "Greg Ewing" <greg.ewing at canterbury.ac.nz> wrote:

C Anthony Risinger wrote:

> Incredibly useful and intuitive, and for me again, way more generally
> applicable than iterable unpacking. Maps are ubiquitous.
>

Maps with a known, fixed set of keys are relatively uncommon
in Python, though. Such an object is more likely to be an
object with named attributes.


I would generally agree, but in the 3 languages I mentioned at least, map
destructuring does not require the LHS to exactly match the RHS (a complete
match is required for lists and tuples though).

Because pattern matching is central to the language, Elixir takes it even
further, providing syntax that allows you to choose whether a variable on
the LHS is treated as a match (similar to the None constant in my example)
or normal variable binding.

In all cases though, the LHS need only include the attributes you are
actually interested in matching and/or binding. I need to review the linked
thread still, but the way ECMAScript does it:

const {one, two} = {one: 1, two: 2};

I think could also be useful in Python, especially if we defined some
default handling of objects and dicts via __getattr__ and/or __getitem__,
because people could use this to destructure `self` (I've seen this
requested a couple times too):

self.one = 1
self.two = 2
self.three = 3
{one, two} = self

Or maybe even:

def fun({one, two}, ...):

Which is also supported (and common) in those 3 langs, but probably less
pretty to Python eyes (and I think a bit less useful without function
clauses).

-- 

C Anthony [mobile]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170608/1ef2c2c0/attachment.html>


More information about the Python-ideas mailing list