Created
December 25, 2021 10:28
-
-
Save ruslanmv/76fe500ebfd3280e65c56a7803932e8a to your computer and use it in GitHub Desktop.
Tricks with Functions in Python: Object-functions, lambda, TryCatch, Currying (Partial)
This file contains 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
## Functions ----------- | |
## Multiple return | |
def f(): | |
a = 5 | |
b = 6 | |
c = 7 | |
return a, b, c | |
a, b, c = f() | |
print(a) | |
print(c) | |
## Alternative Option | |
def f(): | |
a = 5 | |
b = 6 | |
c = 7 | |
return {'a' : a, 'b' : b, 'c' : c} | |
print(f()) | |
## Treated functions as object | |
import re | |
def remove_punctuation(value): | |
return re.sub('[!#?]', '', value) | |
## Put functions by name as a list | |
clean_ops = [str.strip, remove_punctuation, str.title] | |
states = [' Alabama ', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda', | |
'south carolina##', 'West virginia?'] | |
## Combined / Generic function | |
def clean_string(strings, ops): | |
out = [] | |
for s in strings: | |
for function in ops: | |
s = function(s) | |
out.append(s) | |
return out | |
clean_string(states, clean_ops) | |
## Use function name as a argument | |
list(map(remove_punctuation, states)) | |
## Annoynymous lambda function | |
list(map(lambda s: remove_punctuation(str.strip(s)), states)) | |
strings = ['foo', 'card', 'bar', 'aaaa', 'abab'] | |
strings.sort(key=lambda x: len(set(list(x)))) | |
print(strings) | |
## Currying: Partial Argument Application | |
'''Currying is computer science jargon (named after the mathematician Haskell Curry) | |
that means deriving new functions from existing ones by partial argument application''' | |
def add_number(a, b): | |
return a + b | |
add_5_to = lambda b: add_number(5, b) | |
add_number(2, 5) | |
add_5_to(2) | |
from functools import partial | |
add_5_to2 = partial(add_number, a=5) | |
add_5_to2(b=2) | |
## Try Catch ------ | |
def attempt_float(x): | |
try: | |
return float(x) | |
except: ## maybe only ignore some (ValueError, TypeError) | |
return 'Error' | |
finally: ## try block success or not run this | |
print('Done anyway') | |
attempt_float(6) | |
attempt_float('hello') ## ValueError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment