Data Tree urgent help!!!!!!

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Feb 20 06:47:55 EST 2013


Chris Angelico wrote:

>> I'm wondering why you used map.
>>
>>
>> apple, pear, dog, cat, fork, spoon = "apple pear dog cat fork
>> spoon".split()
> 
> Why, in case someone monkeypatched split() to return something other
> than strings, of course!
> 
> Sorry, I've been learning Ruby this week, and I fear it may be
> damaging to my mind...

:-)


You cannot monkey-patch builtins themselves in Python. Since the string is a
literal, it is guaranteed to be a builtin string, and the split method is
guaranteed to be the builtin str.split method.

This is, however, not true in the earlier example of map(str, ...) since
either of map or str could be shadowed by a global function of the same
name, or even monkey-patched across the whole Python environment:

py> import __builtin__  # Python 2.7
py> __builtin__.str = lambda x: len(x)
py> __builtin__.map = lambda func, items: [10000+func(x) for x in items]
py> map(str, "apple, pear, dog".split())
[10006, 10005, 10003]


So unlike Ruby, Python restricts what you can monkey-patch, and discourages
you from doing it even when you can. Oh, and I can reverse my monkey-patch
easily:

py> reload(__builtin__)
<module '__builtin__' (built-in)>
py> map(str, "apple, pear, dog".split())
['apple,', 'pear,', 'dog']



-- 
Steven




More information about the Python-list mailing list