Last active
January 30, 2019 02:50
-
-
Save louisswarren/cc91a06ca0a9a17c475d1cdfafdb0178 to your computer and use it in GitHub Desktop.
Set the return value of a function, but return later
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 returnlater(f): | |
def inner(*args, **kwargs): | |
x = f(*args, **kwargs) | |
r = None | |
while True: | |
try: | |
r = next(x) | |
except StopIteration as final: | |
if final.value is not None: | |
return final.value | |
return r | |
return inner | |
@returnlater | |
def test(x, default=None): | |
if default: | |
yield default | |
if x < 5: | |
yield "x < 5" | |
elif x < 10: | |
yield "x < 10" | |
if x > 100: | |
return "That's too big!" | |
print(test(3)) | |
print(test(8)) | |
print(test(20)) | |
print(test(20, "Unknown")) | |
print(test(1000, "Unknown")) | |
""" | |
x < 5 | |
x < 10 | |
None | |
Unknown | |
That's too big! | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment