diff options
| author | kotfu <kotfu@kotfu.net> | 2018-06-03 15:27:47 -0600 |
|---|---|---|
| committer | kotfu <kotfu@kotfu.net> | 2018-06-03 15:27:47 -0600 |
| commit | 242742b94ea2c11db3929aa1de8b21deadb6fe5c (patch) | |
| tree | e4a6798237f0a173c89ac9e9ffb9be8e6c36ed58 /cmd2 | |
| parent | e5a0f306a16bb06406ba3c6f88821bfe6c8ca738 (diff) | |
| download | cmd2-git-242742b94ea2c11db3929aa1de8b21deadb6fe5c.tar.gz | |
Precommand hooks now check typing of passed callables
Diffstat (limited to 'cmd2')
| -rw-r--r-- | cmd2/cmd2.py | 30 |
1 files changed, 29 insertions, 1 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 69d6224e..89f14b37 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -3127,8 +3127,36 @@ Script should contain one command per line, just like command would be typed in def register_precmd_hook(self, func): """Register a function to be called before the command function.""" + import inspect + signature = inspect.signature(func) + # validate that the callable has the right number of parameters + nparam = len(signature.parameters) + if nparam < 1: + raise TypeError('precommand hooks must have one positional argument') + if nparam > 1: + raise TypeError('precommand hooks take one positional argument but {} were given'.format(nparam)) + # validate the parameter has the right annotation + paramname = list(signature.parameters.keys())[0] + param = signature.parameters[paramname] + if param.annotation != plugin.PrecommandData: + raise TypeError('argument 1 of {} has incompatible type {}, expected {}'.format( + func.__name__, + param.annotation, + plugin.PrecommandData, + )) + # validate the return value has the right annotation + if signature.return_annotation == signature.empty: + raise TypeError('{} does not have a declared return type, expected {}'.format( + func.__name__, + plugin.PrecommandData, + )) + if signature.return_annotation != plugin.PrecommandData: + raise TypeError('{} has incompatible return type {}, expected {}'.format( + func.__name__, + signature.return_annotation, + plugin.PrecommandData, + )) self._precmd_hooks.append(func) - # TODO check signature of registered func and throw error if it's wrong def register_postcmd_hook(self, func): """Register a function to be called after the command function.""" |
