Skip to content

Instantly share code, notes, and snippets.

@TaurusOlson
Created June 16, 2013 19:48
Show Gist options
  • Save TaurusOlson/5793172 to your computer and use it in GitHub Desktop.
Save TaurusOlson/5793172 to your computer and use it in GitHub Desktop.
Converting a function to an elementwise function
def elementwise(fn):
def newfn(arg):
if hasattr(arg,'__getitem__'): # is a Sequence
return type(arg)(map(fn, arg))
else:
return fn(arg)
return newfn
@elementwise
def compute(x):
return x**3 - 1
print compute(5) # prints: 124
print compute([1,2,3]) # prints: [0, 7, 26]
print compute((1,2,3)) # prints: (0, 7, 26)
@TaurusOlson
Copy link
Author

This snippet is extracted from the blog post Charming Python: Decorators make magic easy by David Mertz.
I keep it here because it could be useful for stuffs I do at work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment