Предизвикателства > Abomination decorator > Решения > Решението на Георги Кунчев

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

2 точки общо

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

 1GATE_IN = 'in'
 2GATE_OUT = 'out'
 3
 4
 5def type_check(gate):
 6    """Generate a decorator for validating input or output values."""
 7    assert gate in {GATE_IN, GATE_OUT}, f"Gate not '{GATE_IN}' or '{GATE_OUT}'"
 8    def type_check_per_type(*types):
 9        """Generate a decorator for validating values towards specific types."""
10        assert len(types), f"No types to use. Undefined behaviour."
11        types_repr = ', '.join(map(str, types))
12        def decorator(fun):
13            """A decorator for specific gate and types."""
14            assert callable(fun), "Invalid object. Must be callable."
15            def decorated_in(*args, **kwargs):
16                """A decorated version of the function for input."""
17                args = args + tuple(kwargs.values())
18                if any(map(lambda arg: not isinstance(arg, types), args)):
19                    print(f"Invalid input arguments, expected {types_repr}!")
20                return fun(*args, **kwargs)
21            def decorated_out(*args, **kwargs):
22                """A decorated version of the function for output."""
23                if not isinstance(result:=fun(*args, **kwargs), types):
24                    print(f"Invalid output value, expected {types_repr}!")
25                return result
26            return {GATE_IN: decorated_in, GATE_OUT: decorated_out}[gate]
27        return decorator
28    return type_check_per_type
29
30
31# Pretty much the same as above, but defined in a single line
32#type_check = lambda gate: lambda *types: lambda fun: lambda *args, **kwargs: (result:=fun(*args, **kwargs), gate == GATE_IN and any(map(lambda arg: not isinstance(arg, types), args + tuple(kwargs.values()))) and print(f"Invalid input arguments, expected {', '.join(map(str, types))}!"), gate == GATE_OUT and not isinstance(result, types) and print(f"Invalid output value, expected {', '.join(map(str, types))}!"))[0]

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)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/solution.py", line 23, in decorated_out
if not isinstance(result:=fun(*args, **kwargs), types):
^^^^^^^^^^^^^^^^^^^^
File "/tmp/solution.py", line 20, in decorated_in
return fun(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^
TypeError: lonely_island() takes 2 positional arguments but 3 were given

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

FAILED (errors=1)

Дискусия
Михаил Цанков
24.10.2024 21:22

За първи път виждам, че качвате решения. Найс
История
Това решение има само една версия.