Using String Methods In Jump Tables
Terry Reedy
tjreedy at udel.edu
Mon Aug 23 13:41:02 EDT 2010
On 8/23/2010 11:57 AM, Tim Daneliuk wrote:
> On 8/23/2010 10:35 AM, Jon Clements wrote:
>> Another more generic option would be to use methodcaller from the
>> operator module.
> Could you say a bit more about just why you prefer this approach?
> Clearly, it *is* more generic, but in looking it over, it seems that
> methodcaller is less readable and intuitive ... at least to my eyes ...
He did not say 'preferable', only more generic, as you agree, and the
generic solution, buried away in operator, is a good thing to know about.
The OP wanted to convert (methodname, string) pairs to a call of
methodname on strings. Since there is only one class, str, involved,
mapping methodname to str.methodname works. If, for instance, the OP
instead had to map (methodname, bytes_or_string) to a call, a not
unreasonable generalization, str.methodname does not work (with bytes)
but methodcaller(methodname) will, with bytes or string.
>>> methodcaller('upper')(b'abc')
b'ABC'
>>> methodcaller('upper')('abc')
'ABC'
--
Terry Jan Reedy
More information about the Python-list
mailing list