Created
June 16, 2013 19:48
-
-
Save TaurusOlson/5793172 to your computer and use it in GitHub Desktop.
Converting a function to an elementwise function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.