[Python-ideas] Unpack of sequences
Steven D'Aprano
steve at pearwood.info
Wed Aug 29 19:01:09 CEST 2012
On 30/08/12 02:10, Mike Graham wrote:
> On Wed, Aug 29, 2012 at 11:45 AM, Masklinn<masklinn at masklinn.net> wrote:
>> On 2012-08-29, at 17:03 , Guido van Rossum wrote:
>>>
>>> Also of course assignment has no equivalent to keyword parameters
>>
>> I've always thought it would be a rather neat way to unpack
>> dictionaries, instead of doing it by hand or abusing `itemgetter` to get
>> values in a known order.
>
> Do you have a suggestion of a nice syntax for a thing to unpack
> mappings (or to unpack things by attributes)?
a, b, x, y = **mapping
could be equivalent to:
a, b, x, y = mapping['a'], mapping['b'], mapping['x'], mapping['y']
I don't have good syntax for the attribute equivalent, but I do have
bad syntax for it:
a, b, x, y = **.obj
# like a, b, x, y = obj.a, obj.b, obj.x, obj.y
Or you could use wrap your object in a helper class:
class AttrGetter:
def __init__(self, obj):
self.obj = obj
def __getitem__(self, key):
return getattr(self.obj, key)
a, b, x, y = **AttrGetter(obj)
--
Steven
More information about the Python-ideas
mailing list