5

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.

1
  • you're missing a ":" after (arg2) in your if statement Commented Jun 6, 2018 at 7:20

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.