Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to execute a statement before each return statement in python function?

For example i have this piece of code:

def example():
    a = 'goodbye'
    if True:
        print a
        return 1
    else:
        print a
        return 0

I would like to know if there is any possible solution to write once "print a" and execute it before each "return" statement automaticaly. So that if I add more return statements I wouldn't need to add anything, but "print a" would execute. Result would look like something:

def example():
    a = "goodbye"
    """ some code to implement print a """
    if True:
        return 1
    else:
        return 0

Each time there is return statement it still would print a.

I tried to google, but don't know how word query, since all results are about returning multiple values.

UPDATE: My question was answered, thanks to all of you.
Although wrapping functions are correct answer, but I have chosen answer by GingerPlusPlus who suggested to use try...finally for simplicity.

like image 778
Dmitry Avatar asked Feb 11 '16 10:02

Dmitry


People also ask

Can a Python function have multiple return statements?

Python functions are not restricted to having a single return statement. If a given function has more than one return statement, then the first one encountered will determine the end of the function's execution and also its return value.

Can a function have multiple return statements?

A function can have more than one return statement, but only ever run one based on a condition.

How do I make sure a function only runs once in Python?

To run a function only once:Change the value of the global variable to True in the function. Only run the code in the function if the global variable is set to False .

Is it possible to have a return value in an expression in Python?

The python return statement is used to return the output from a function. We learned that we can also return a function from another function. Also, expressions are evaluated and then the result is returned from the function.


2 Answers

try .. finally:

def example():
    try:
       if True:
           return 1
       else:
           return 0
    finally:
        print 'goodbye'

>>> example()
goodbye
1

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. Docs

like image 132
GingerPlusPlus Avatar answered Oct 07 '22 21:10

GingerPlusPlus


You can use a context. Initialize it with the value you want to print. Then print when context exit, i.e. upon return.

class PrinterOnContextExit():
    def __init__( self, a ): self.a = a
    def __enter__( self ): pass
    def __exit__( self, exc_type, exc_value, traceback ): print( self.a )

def example():
    a = 'goodbye'
    with PrinterOnContextExit( a ):
        if True:
            return 1
        else:
            return 0

Note that you cannot print the returned value this way. If you ever wanted to print the returned value, then you should use a decorator.

class PrintOnReturn():
    def __init__( self, a ): self.a = a
    def __call__( self, func ): return lambda *args, **kwargs: self.callFunc( func, *args, **kwargs )
    def callFunc( self, func, *args, **kwargs ): r = func( *args, **kwargs ); print( self.a, r ); return r

@PrintOnReturn( "hello" )
def example():
    if True:
        return 1
    else:
        return 0

This will print whatever string you passed to the decorator, followed by the value returned from the decorated function. Here hello 1.

like image 41
Didier Trosset Avatar answered Oct 07 '22 23:10

Didier Trosset