Challenge: Flexible Type Validation Decorator
Tarea
Swipe to start coding
Create a flexible decorator for validating data types:
-
Define the validate decorator, which should take data types (
str
,int
,bool
, etc.) as arguments and annotate them using thetype
keyword. -
Define the
inner
function that takes a function (func
) as an argument. -
Define the
wrapper
function that takes*args
. -
Check if each argument is an instance of one of the specified
types
. -
Functions should return:
- The
wrapper()
should return the result offunc()
with the provided arguments. - The
inner()
should returnwrapper
without calling it. - The
validate()
should returninner()
without calling it.
-
Validate the
snake_string()
function for thestr
data type using the@validate
decorator. -
Validate the
multiply()
function for theint
orfloat
data types using the@validate
decorator.
Solución
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def validate(*types: type):
def inner(func):
def wrapper(*args):
for item in args:
if not isinstance(item, types):
raise TypeError(f"The function expect the types: {list(types)}")
return func(*args)
return wrapper
return inner
@validate(str)
def snake_string(*args):
return "-".join(args)
@validate(int, float)
def multiply(*args):
result = 1
for num in args:
result *= num
return round(result, 2)
try:
print(snake_string("I", "am", "a", "long", "snake"))
print(snake_string(1, 2, 3, 4))
except TypeError as error:
print("TypeError:", error)
try:
print(multiply(12, 1.6, 31, 14))
print(multiply("123", "321512"))
except TypeError as error:
print("TypeError", error)
¿Todo estuvo claro?
¡Gracias por tus comentarios!
Sección 3. Capítulo 6
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def ___(*types: ___):
def inner(___):
def ___(___):
for item in args:
if not isinstance(item, ___):
raise TypeError(f"The function expect the types: {list(types)}")
return ___(*args)
return ___
return ___
___(___)
def snake_string(*args):
return "-".join(args)
___(___, ___)
def multiply(*args):
result = 1
for num in args:
result *= num
return round(result, 2)
try:
print(snake_string("I", "am", "a", "long", "snake"))
print(snake_string(1, 2, 3, 4))
except TypeError as error:
print("TypeError:", error)
try:
print(multiply(12, 1.6, 31, 14))
print(multiply("123", "321512"))
except TypeError as error:
print("TypeError", error)
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla