PEP Idea: Multi-get for lists/tuples and dictionaries (inspired in NumPy)

Chris Angelico rosuav at gmail.com
Thu Mar 19 11:44:54 EDT 2020


On Fri, Mar 20, 2020 at 2:37 AM Terry Reedy <tjreedy at udel.edu> wrote:
>
> On 3/18/2020 10:28 PM, Santiago Basulto wrote:
>
> > For dictionaries it'd even be more useful:
> >      d = {
> >          'first_name': 'Frances',
> >          'last_name': 'Allen',
> >          'email': 'fallen at ibm.com'
> >      }
> >      fname, lname = d[['first_name', 'last_name']]
>
> Insert ordered dicts make this sort of thing less useful.
>
>  >>> d = {
>          'first_name': 'Frances',
>          'last_name': 'Allen',
>          'email': 'fallen at ibm.com'
> }
>  >>> fname, lname, _ = d
>  >>> fname, lname
> ('first_name', 'last_name')
>

Uhh, great, but the OP wanted fname = "Frances" and lname = "Allen" :)

But even using d.values() here isn't really a solution. It's assuming
positional information where the code really wants to be grabbing
named attributes.

JavaScript has an elegant syntax for object destructuring:

let { first_name, last_name } = d

Python can do this for positional unpacking, but not for named
attributes. The OP's proposal would allow the existing unpacking
syntax to be used for this, simply by returning an unpackable entity
(a list or tuple).

ChrisA


More information about the Python-list mailing list