Created
November 10, 2018 13:18
-
-
Save kurogelee/1fd89e02b75cab4aa08be2d5fd3c149c to your computer and use it in GitHub Desktop.
デコレータとyieldを使ってdictを返す関数でちょっと楽する方法 ref: https://qiita.com/kurogelee/items/1c081a5a7e209e81921c
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 returns(wrap_function): | |
def decorator(f): | |
def decorated(*args, **kwargs): | |
return wrap_function(f(*args, **kwargs)) | |
return decorated | |
return decorator |
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
@returns(dict) | |
def times3(values): | |
for v in values: | |
yield v, v * 3 | |
print(times3([1, 3, 5])) # {1: 3, 3: 9, 5: 15} |
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 times3_old(values): | |
result = {} | |
for v in values: | |
result[v] = v * 3 | |
return result | |
print(times3_old([1, 3, 5])) # {1: 3, 3: 9, 5: 15} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment