Last active
May 8, 2020 05:49
-
-
Save louisswarren/160891bd9d259db561a1d29bd818834c to your computer and use it in GitHub Desktop.
Cast using python type annotations
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 cast(f): | |
returns = f.__annotations__['return'] | |
if callable(returns): | |
casters = returns, | |
else: | |
casters = reversed(returns) | |
def inner(*args, **kwargs): | |
r = f(*args, **kwargs) | |
for caster in casters: | |
r = caster(r) | |
return r | |
return inner | |
@cast | |
def nums() -> dict: | |
yield 1, 'one' | |
yield 2, 'two' | |
@cast | |
def hello() -> (str.upper, ', '.join): | |
yield "Hello" | |
yield "world" | |
print(repr(nums())) | |
print(repr(hello())) | |
""" | |
{1: 'one', 2: 'two'} | |
'HELLO, WORLD' | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment