[Python-ideas] Method chaining notation

Ron Adam ron3200 at gmail.com
Wed Feb 26 21:54:30 CET 2014



On 02/26/2014 01:55 PM, Andrew Barnert wrote:
> From: Ron Adam<ron3200 at gmail.com>
>
> Sent: Wednesday, February 26, 2014 7:28 AM
>
>
>> >Dictionaries are pretty flexible on how they are initiated, so it's
>> >surprising we can't do this...
>> >
>> >         D = dict(keys=names, values=args)
>> >
>> >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.
>
> Sounds like you're thinking in Smalltalk/ObjC terms, both the "with" name and the expecting two "withs":
>
>      [NSDictionary dictionaryWithObjects:values forKeys:keys]
>
> The reason we don't need this in Python is that the default construction method takes key-value pairs, and you can get that trivially from zip:
>
>      dict(zip(keys, values))
>
> Would it really be more readable your way?
>
>      dict.withkeys(keys, values=values)
>
> Yes, to novices who haven't internalized zip yet. I guess the question is whether requiring people to internalize zip early is a good thing about Python, or a problem to be solved. It's not like we're requiring hundreds of weird functional idioms to make everything as brief as possible, just a very small number, each an abstraction that works consistently across a broad range of uses.

The reason I expected to be able to do that is you can get just keys, or 
values from a dict...  dict.keys() dict.values(), and pairs.. dict.items(). 
  It just makes sense that it will take those directly too.  I'm sure I'm 
not the only one who thought that.

I don't really buy the because we can do... ... and get... as a valid 
reason by it's self not to do something.  Not when it's clearly related to 
the objects type as keys, and values are.  For unrelated things, yes, it is 
a valid reason.

For example you could say, we don't need dict.items because we can do...

      zip(dict.keys(), dict.values())

Or we don't need dict.keys() and dict.values because we can do...

     [x for x, y in dict.items()]
     [y for x, y in dict.itmes()]

But dictionaries are used so often that having these methods really helps 
to make the code more readable and easy to use.  (or beautiful to the eye 
of the programmer)

In any case.. It's just my opinion.  Not trying to convince anyone we need 
it or to do it.  If it was really needed, we'd have it already.  (although 
that argument isn't very strong either. ;-)

Cheers,
    Ron



More information about the Python-ideas mailing list