Return and print without assigning a variable?

Curiously, is there a way for both printing and returning within a single function without assigning output to a variable?

Consider this code:

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

Is there a way to refer to this variable stored for the return statement?

+5
source share
1 answer

I think there is no direct or โ€œeasyโ€ way to do this. However, one way would be to define a decorator that prints this. For instance:

  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) 
+5
source

Source: https://habr.com/ru/post/1214704/


All Articles