2009-05-27

ObjectMap

I like how Python ensures no library messes with my built-ins. The fact that neither I can monkey patch built-ins is however a pain, interestingly while built-ins can't be extended they can be decorated/overriden, and lo I present unto you, ObjectMap.


class ObjectMap(object):
def __init__(self):
"""Did you look what I did there?"""
self.map = map
def __call__(self, *args, **kwargs):
"""The original map call"""
return self.map(*args, **kwargs)
def __getattr__(self, name):
"""map.name(sequence, args) == [item.name(args) for item in sequence]
Here is the fun part"""
def fn(seq, *args, **kwargs):
return self.map(lambda item: getattr(item, name)(*args, **kwargs) , seq )
return fn
map = ObjectMap():
words = "red green blue".split()
WORDS1 = map(lambda word: word.upper(), words)
WORDS2 = [word.upper() for word in words]
WORDS3 = map.upper(words)
assert WORDS1 == WORDS2 == WORDS3


Needless to say, this shouldn't be used in production code (so use it copiously).