[Python-ideas] Method chaining notation

Andrew Barnert abarnert at yahoo.com
Wed Feb 26 20:55:58 CET 2014


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.


More information about the Python-ideas mailing list