Multiple return values ​​in python

I want to change python function to return two values. How to achieve this without affecting any of the previous function calls that expect only one return value?

For instance,

Original definition:

def foo():
    x = 2
    y = 2
    return (x+y)

sum = foo ()

Ne Definition:

def foo():
    x = 2
    y = 2
   return (x+y), (x-y)

sum, diff = foo ()

I want to make this so that the previous foo call also remains valid? Is it possible?

+5
source share
3 answers
def foo(return_2nd=False):

    x = 2
    y = 2
    return (x+y) if not return_2nd else (x+y),(x-y)

then call the new version

sum, diff = foo(True)
sum = foo() #old calls still just get sum
+12
source

By changing the type of the return value, you change the "contract" between this function and any code that calls it. Therefore, you should probably change the code that calls it.

, , set . . . , , .

+2

Sorry, but the overload function is not valid in Python. Because Python does not force type execution, several foo definitions result in the use of the last valid. One of the common solutions is to define several functions or add a parameter to the function as a flag (which you need to implement yourself)

0
source

All Articles