Uday Kumar
Uday Kumar

Reputation: 71

how to validate arguments using decorators in python

I need to validate two given inputs before I call the add function: Ff any input is not an integer I should get invalid input or error message, if both are integers I should get the sum.

import re

def my_dec(arg1,arg2):
     x = re.compile(r"[^0-9]")
     if x.search(arg1) and x.search(arg2):
        return add(a,b)
     else:
         print("invalid input")

@my_dec(arg1,arg2)
def add(a,b):
   return a + b

print(add(2,3))

I get function not defined errors in loops, but I don't know how to overcome it.

Upvotes: 5

Views: 3800

Answers (3)

Evgeniy_Burdin
Evgeniy_Burdin

Reputation: 703

from valdec.decorators import validate
from valdec.errors import ValidationArgumentsError


@validate
def add(a: int, b: int) -> int:
   return a + b

assert add(2, 3) == 5

try:
    add("s", 3)
except ValidationArgumentsError:
    pass

valdec: https://github.com/EvgeniyBurdin/valdec

Upvotes: 1

Uday Kumar
Uday Kumar

Reputation: 71

After lot of research and work, I found the solution to validate the values and find the addition of two values using decorators.

import random

def decorator(func):
    def func_wrapper(x,y):
        if type(x) is int and type(y) is int:
            result = func(x,y)
            print(f"{x} + {y} = {result}")
            return result
        elif type(x) is not int or type(y) is not int:
            print("invalid input")
    return func_wrapper

def add(a, b):
    return a+b

Call the add function before decorator:

print(add(4, 5))
    
add = decorator(add)

#check for different values and inputs
list_1 = [1, 2, 32, 4, 4, 65, 3, 2, 'A', 'D', None, False, True,
          0, 1, -2, 2, -33, 0.223, 212, 'string']
for i in range(1, 100):
    x = random.choice(list_1)
    y = random.choice(list_1)
    add(x, y)

Upvotes: 2

Ramesh Kumar
Ramesh Kumar

Reputation: 11

Decorator takes in a function, add functionality and returns it. Refer the below code which solves your issue:

import re

def my_dec(func_name):

    def sub_dec(a, b):
        if re.match(r'\d',str(a)) and re.match(r'\d',str(b)):
            return func_name(a,b)
        else:
            print("invalid input")

    return sub_dec


@my_dec
def add(a,b):
    return a + b

print(add(2,3))

Upvotes: 1

Related Questions