Skip to content

Instantly share code, notes, and snippets.

@pirate
Created April 26, 2017 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirate/a69f17453cb5106899b7dbf769451686 to your computer and use it in GitHub Desktop.
Save pirate/a69f17453cb5106899b7dbf769451686 to your computer and use it in GitHub Desktop.
def autocast(func):
"""Tries to cast any parameters with type hints to the type defined.
Will not act if more than one type is defined.
Try to avoid using this, instead type-cast within your function to the desired types."""
def autocast_wrapper(*args, **kwargs):
sig = signature(func)
def convert(arg, param):
try:
annotation = sig.parameters[param].annotation
except KeyError:
annotation = _empty
# magic
if annotation is not _empty and annotation.__class__ is type:
if not isinstance(arg, annotation):
return annotation(arg)
return arg
new_args = [convert(arg, param) for arg, param in zip(args, sig.parameters)]
new_kwargs = {param: convert(arg, param) for param, arg in kwargs.items()}
return func(*new_args, **new_kwargs)
return autocast_wrapper
### Example usage
@autocast
def on_deal(self, card: Card, offset: int) -> bool:
board = self.board
board.append(card)
self.board[-1 if offset is None else offset] = board
self.on_record_action()
return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment