Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning and printing without assigning to variable?

Tags:

python

Just curious if there is a way to both print and return within one function without assigning the output to variable?

Consider this code:

def secret_number(secret_number_range):
    return random.randrange(1, secret_number_range + 1)

Is there a way to reference that variable stored for the purpose of return statement?

like image 804
Blücher Avatar asked Mar 05 '15 01:03

Blücher


1 Answers

I think there is no any direct or "easy" way of doing this. However, one way would be to define a decorator that prints this. For example:

    import random        

    def print_return(func):
        def func_wrapper(param):
            rv =   func(param)
            print("Return value: {0}".format(rv))
            return rv
        return func_wrapper

    @print_return
    def secret_number(secret_number_range):
        return random.randrange(1, secret_number_range + 1)

    # with this, this call would result in "Return value: 3" being printed.
    c=secret_number(4)
like image 199
Marcin Avatar answered Oct 13 '22 23:10

Marcin