Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active May 8, 2020 05:49
Show Gist options
  • Save louisswarren/160891bd9d259db561a1d29bd818834c to your computer and use it in GitHub Desktop.
Save louisswarren/160891bd9d259db561a1d29bd818834c to your computer and use it in GitHub Desktop.
Cast using python type annotations
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