[Python-ideas] Collect **kw arguments as an ordered dictionary

Masklinn masklinn at masklinn.net
Sat Sep 5 16:39:14 CEST 2009


Response to a fairly old (April) thread, but there's another use case  
to **kwargs being collected in an ordered dictionary: interaction with  
Objective-C or Smalltalk (but mainly obj-c/Cocoa): since **kwargs is  
not an ordered dict, Python/Cocoa interop can't use them to emulate  
ObjC's compound message names (as order is significant), so PyObjC  
merges the message subparts into a single method and tacks the  
arguments at the end, transforming calls like

     [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames"
                               encoding:NSASCIIStringEncoding
                                  error:&error];

into

     NSString.stringWithContentsOfFile_encoding_error_(
                 "/usr/share/dict/propernames",
                 NSASCIIStringEncoding)

while the verbosity is similar, the loss in readability is tremendous.  
With the availability of ordered **kwargs, the bridge could simply  
have a send method (akin to the ObjC performSelector:) taking a bunch  
of kwargs and sending the corresponding message to the underlying ObjC  
object:

     NSString.send(stringWithContentOfFile="/usr/share/dict/ 
propernames",
                   encoding=NSASCIIStringEncoding,
                   error=errors)

Or variable method names with a bit of massaging e.g. using the first  
message part as the method name à la MacRuby:

     NSString.stringWithContentOfFile("/usr/share/dict/propernames",
                             encoding=NSASCIIStringEncoding,
                                error=errors)

or splitting that first part between the method name and the first  
kwarg:

     NSString.stringWith(ContentOfFile="/usr/share/dict/propernames",
                         encoding=NSASCIIStringEncoding,
                         error=errors)


More information about the Python-ideas mailing list