Предизвикателства > Abomination decorator > Решения > Решението на Марина Господинова

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

2 точки общо

4 успешни теста
0 неуспешни теста
Код

 1def show_message(valid_types, operation):
 2    """Display error messages."""
 3    valid_types_mess = ', '.join([str(i) for i in valid_types])
 4    if operation == "in":
 5        print(f"Invalid input arguments, expected {valid_types_mess}!")
 6    if operation == "out":
 7        print(f"Invalid output value, expected {valid_types_mess}!")
 8
 9def check_error(valid_types, args, operation, opt={}):
10    """Show if there is an error."""
11    if operation == "in" and not all(type(arg) in valid_types for arg in args):
12            show_message(valid_types, operation)
13    elif operation == "in" and not all(type(kwarg) in valid_types for kwarg in opt.values()):
14            show_message(valid_types, operation)
15    elif operation == "out" and type(args) not in valid_types:
16            show_message(valid_types, operation)
17
18def type_check(operation):
19    """Check valid types of in and out objects."""
20    def decorator_for_types(*allowed_types):
21        valid_types = tuple(allowed_types)
22        def decorator_for_func(func):
23            def decorated(*args, **kwargs):
24                if operation == "in":
25                    check_error(valid_types, args, operation, kwargs)
26                result = func(*args, **kwargs)
27                if operation == "out":
28                    check_error(valid_types, result, operation)
29                return result
30            return decorated
31        return decorator_for_func
32    return decorator_for_types

....
----------------------------------------------------------------------
Ran 4 tests in 0.002s

OK

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