Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python decorator not behaving as expected

I have this code from following this tutorial on YouTube. I cannot wrap my head around why div(10, 2) would give the same output as div(10, 0), in both cases None. Can someone tell me what is wrong with it and what is the way to make it work with a result of 5 when dividing 10/2?

def check(func):
    def inside(a, b):
      if b == 0:
        print ("Can't divide by 0")
        return 
      func(a, b)
    return inside
    

@check
def div(a, b):
  return a/b

print(div(10, 2))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the code you posted, the div function returns the result of a/b without printing it. However, the inside function in the check decorator does not return this result. Instead, it prints a message and returns None if b is 0. This is why calling div(10, 2) and div(10, 0) both print the message and return None.

To make the code work as intended, you can add a return statement to the inside function that returns the result of calling func(a, b). This will return the result of the division instead of None when b is not 0.

Here is an example of how you could modify the code to do this:

def check(func):
    def inside(a, b):
        if b == 0:
            print("Can't divide by 0")
            return 
        return func(a, b)  # Return the result of the division
    return inside


@check
def div(a, b):
    return a/b

print(div(10, 2))

With this change, calling div(10, 2) will return the result of the division, which is 5. Calling div(10, 0) will print the message and return None, as before.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading