[Python-ideas] Method chaining notation

Ron Adam ron3200 at gmail.com
Wed Feb 26 16:28:30 CET 2014



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)

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