Предизвикателства > Abomination decorator > Решения > Решението на Йована Божилов

Резултати
2 точки от тестове
0 точки от учител

2 точки общо

3 успешни теста
1 неуспешни теста
Код

 1def type_check(check_type):
 2    def decorator(*valid_argument_types):
 3        def wrapper(func):
 4            def inner(*args):
 5                if check_type == "in":
 6                    if not all(isinstance(arg, valid_argument_types) for arg in args):
 7                        types = ", ".join([str(t) for t in valid_argument_types])
 8                        print(f"Invalid input arguments, expected {types}!")
 9
10                result = func(*args)
11
12                if check_type == "out":
13                    if not isinstance(result, valid_argument_types):
14                        types = ", ".join([str(t) for t in valid_argument_types])
15                        print(f"Invalid output value, expected {types}!")
16
17                return result
18            return inner
19        return wrapper
20    return decorator
21
22@type_check("in")(int, float, complex)
23def power(num, power):
24    return num ** power
25
26@type_check("in")(str)
27@type_check("out")(str)
28def concatenate(*strings, separator=' beep boop '):
29    return separator.join(strings)

E...
======================================================================
ERROR: test_check_both (test.TestTypeCheck.test_check_both)
The decorator should report invalid "in" and "out" together.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.12/unittest/mock.py", line 1390, in patched
return func(*newargs, **newkeywargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/test.py", line 97, in test_check_both
result = decorated("Captain Jack Sparrow", "Bill", pirates=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: type_check.<locals>.decorator.<locals>.wrapper.<locals>.inner() got an unexpected keyword argument 'pirates'

----------------------------------------------------------------------
Ran 4 tests in 0.003s

FAILED (errors=1)

Дискусия
История
Това решение има само една версия.