[Python-ideas] Method chaining notation
Masklinn
masklinn at masklinn.net
Wed Feb 26 17:00:24 CET 2014
On 2014-02-26, at 16:28 , Ron Adam <ron3200 at gmail.com> wrote:
>
>
> On 02/26/2014 01:19 AM, Stephen J. Turnbull wrote:
>> Ron Adam writes:
>>
>> > > > def names(defaults, pos_names, pos_args, kwds):
>> > > > return {}.=update(defaults) \
>> > > > .=update(zip(pos_names, pos_args) \
>> > > > .=update(kwds)
>>
>> > > def names(defaults, pos_names, pos_args, kwds):
>> > > for dct in pos_names, pos_args, kwds:
>> > > defaults.update(dct)
>> > > return defaults
>> >
>> > Not quite the same but close. I just tried to come up with a more
>> > realistic example without having to look up a lot code. How does
>> > pos_args in your example get paired with names?
>>
>> Sorry, I knew that before dinner but forgot after dinner. Same way as
>> in yours:
>>
>> def names(defaults, pos_names, pos_args, kwds):
>> for dct in zip(pos_names, pos_args), kwds:
>> defaults.update(dct)
>> return defaults
>
> Yes, ok.
>
>> If that doesn't work in my version (I've never used zip that way), how
>> does it work in yours? BTW, I'd actually be more likely to write that
>> now as
>>
>> def names(defaults, *updates):
>> for update in updates:
>> defaults.update(update)
>> return defaults
>>
>> and call it with "names(zip(pos_names, pos_args), kwds)".
>
> The main difference between this and the one I posted is in this, defaults is mutated in your version. I'd prefer it not be.
>
> Dictionaries are pretty flexible on how they are initiated, so it's surprising we can't do this...
>
> D = dict(keys=names, values=args)
You can. It may not do what you want, but you definitely can do this:
>>> dict(keys=names, values=args)
{'keys': ['a', 'b', 'c', 'd'], 'values': [0, 1, 2]}
Although you're probably looking for:
>>> dict(zip(names, args))
{'a': 0, 'c': 2, 'b': 1}
and if you want to do a fill because you don't have enough args:
>>> dict(izip_longest(names, args, fillvalue=None))
{'a': 0, 'c': 2, 'b': 1, 'd': None}
(itertools is like friendship, it's bloody magic)
> The .fromkeys() method is almost that, but sets all the values to a single value. I think I would have written that a bit different.
>
> def fromkeys(self, keys, values=None, default=None):
> D = {}
> if D is not None:
> D.update(zip(keys, values)]
> for k in keys[len(vaues):]:
> D[k] = default
> return D
>
> And probably named it withkeys instead of fromkeys. <shrug> It's what I expected fromkeys to do.
>
> cheers,
> Ron
>
More information about the Python-ideas
mailing list