Created
April 26, 2017 08:50
-
-
Save pirate/a69f17453cb5106899b7dbf769451686 to your computer and use it in GitHub Desktop.
This file contains 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 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