Magmurrr
Magmurrr

Reputation: 248

If statement that operates on the condition if a function returns None

I have a decorator that just repeats a function a set number of times. The decorator works completely fine, just one small issue. When used on functions that don't return anything. It will print "None" after executing the function. I know that when you print a function that doesnt return anything it just prints "None".

def repeat(r):
    """Decorator that repeats function 'r' number of times"""
    def repetition(f):
        def wrapper(*args, **kwargs):
            for x in range(r):
                rv = f(*args, **kwargs)
                print(rv)

        return wrapper

    return repetition


@repeat(2)
def output(msg):
    print(msg)


@repeat(3)
def addition(*args, result=0):
    for arg in args:
        result += arg

    return result


output("Hello")

addition(1, 2, 3, 4, 5)

Is it possible for me to have an if statement that checks if the function returns None and operates off of that? I would like to add a condition to the decorator so if a function returns nothing it wont print it, therefore stopping it from printing "None" every time it's used on a function that returns nothing.

For Example:

if function() == None:
        do something

Upvotes: 1

Views: 789

Answers (2)

MarianD
MarianD

Reputation: 14141

Instead of your

print(rv)

use

if rv is not None:
     print(rv)

The None value is a singleton, so instead of comparing its value with common operators ==, != (which is possible, but not recommended), compare it with is or is not operators.


Note:

In Python 3.8+ you may use the walrus operator (:=) for assigning a value and compare immediately using it in just one expression:

if (rv := f(*args, **kwargs)) is not None:
    print(rv)

Upvotes: 1

Alejandro Condori
Alejandro Condori

Reputation: 864

Just Check the rv result:

def repeat(r):
    """Decorator that repeats function 'r' number of times"""
    def repetition(f):
        def wrapper(*args, **kwargs):
            for x in range(r):
                rv = f(*args, **kwargs)
                if rv is not None:
                    print(rv)
                else:
                    ## Do domething if the function returns None
        return wrapper
    return repetition

Upvotes: 1

Related Questions