Skip to content

Commit

Permalink
class method callback support
Browse files Browse the repository at this point in the history
  • Loading branch information
HugeBrain16 committed Jul 23, 2021
1 parent 1842b84 commit ebe7fd2
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions cmdtools.py
Expand Up @@ -4,7 +4,7 @@
import shlex
import inspect

__version__ = "2.1.0"
__version__ = "2.2.0"

_CVT_FLOAT_PTR = re.compile(r"^[-+]?(\d*[.])\d*$")
_CVT_INT_PTR = re.compile(r"^[-+]?\d+$")
Expand Down Expand Up @@ -178,11 +178,15 @@ def process_cmd(self, callback, error_handler_callback=None, attrs=None):
if attrs is None:
attrs = {}

if type(callback).__name__ != "function":
raise TypeError("callback is not a function")
if (
inspect.isfunction(callback) is False
and inspect.ismethod(callback) is False
):
raise TypeError("callback is not a function or method")
if (
error_handler_callback
and type(error_handler_callback).__name__ != "function"
and inspect.isfunction(error_handler_callback) is False
and inspect.ismethod(callback) is False
):
raise TypeError("error handler callback is not a function")

Expand All @@ -202,6 +206,11 @@ def process_cmd(self, callback, error_handler_callback=None, attrs=None):
cparams = cargspec.args
cdefaults = cargspec.defaults

# remove 'self' or 'cls' from parameters if method
if inspect.ismethod(callback):
if len(cparams) > 0:
cparams = cparams[1:]

if cdefaults is None:
if len(self.parsed_command["args"]) < len(cparams):
raise MissingRequiredArgument(
Expand Down Expand Up @@ -270,13 +279,15 @@ async def aio_process_cmd(self, callback, error_handler_callback=None, attrs=Non
if attrs is None:
attrs = {}

if type(callback).__name__ != "function":
raise TypeError("callback is not a function")
if inspect.iscoroutinefunction(callback) is False:
raise TypeError("callback is not a coroutine function")
if (
error_handler_callback
and type(error_handler_callback).__name__ != "function"
and inspect.iscoroutinefunction(error_handler_callback) is False
):
raise TypeError("error handler callback is not a function")
raise TypeError(
"error handler callback is not a coroutine function function"
)

if not isinstance(attrs, dict):
raise TypeError("attributes must be in dict object")
Expand All @@ -294,6 +305,11 @@ async def aio_process_cmd(self, callback, error_handler_callback=None, attrs=Non
cparams = cargspec.args
cdefaults = cargspec.defaults

# remove 'self' or 'cls' from parameters if method
if inspect.ismethod(callback):
if len(cparams) > 0:
cparams = cparams[1:]

if cdefaults is None:
if len(self.parsed_command["args"]) < len(cparams):
raise MissingRequiredArgument(
Expand Down

0 comments on commit ebe7fd2

Please sign in to comment.