Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Flexible Type Validation Decorator | Decorators
Mastering Python: Closures and Decorators

book
Challenge: Flexible Type Validation Decorator

Tarea

Swipe to start coding

Create a flexible decorator for validating data types:

  1. Define the validate decorator, which should take data types (str, int, bool, etc.) as arguments and annotate them using the type keyword.

  2. Define the inner function that takes a function (func) as an argument.

  3. Define the wrapper function that takes *args.

  4. Check if each argument is an instance of one of the specified types.

  5. Functions should return:

  • The wrapper() should return the result of func() with the provided arguments.
  • The inner() should return wrapper without calling it.
  • The validate() should return inner() without calling it.
  1. Validate the snake_string() function for the str data type using the @validate decorator.

  2. Validate the multiply() function for the int or float data types using the @validate decorator.

Solución

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?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 6
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

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt