GLaDOS/irc_api/test.py

50 lines
1.3 KiB
Python

def convert(data, new_type, default=None):
try:
return new_type(data)
except:
return default
def check_args(bot, func, *input_args):
# args[0] = (type, is_optionnal)
defaults = getattr(func, "__defaults__")
if not defaults:
defaults = []
annotations = getattr(func, "__annotations__")
if not annotations:
return []
required_args = len(annotations) - len(defaults)
check_args = []
for index, arg_type in enumerate(annotations.values()):
if index + 1 > required_args:
check_args.append((arg_type, defaults[index - required_args]))
else:
check_args.append((arg_type, None))
if len(input_args) < required_args:
# bot.send("Erreur : argument manquant")
return
converted_args = []
for index, arg in enumerate(check_args):
if len(input_args) > index:
converted_args.append(convert(input_args[index], *check_args[index]))
else:
converted_args.append(check_args[index][1])
return converted_args
def foo(bot, msg, a: str, b: int=1):
return None
print(check_args(None, foo, "3"))
print(check_args(None, foo, "3", "5"))
print(check_args(None, foo, "3", "test"))
print(check_args(None, foo, "3", "5", "2", "5"))