简体   繁体   中英

How to check which return statement was executed in a function?

Hi i have a simple function:

def check_val(value):
    if value < 10:
        previous = value
        return previous
    else:
        current  = value + 10
        return current

a = check_val(3)

How can I know if current or previous was returned?

You can have your function return a tuple with the necessary meta and unpack via sequence unpacking:

def check_val(value):
    if value < 10:
        previous = value
        return previous, 'previous'
    else:
        current  = value + 10
        return current, 'current'

a, b = check_val(3)

print(a, b)

3 previous

You can't unless you return a tuple with a flag specifying where you exited

def check_val(val):
    if value < 10:
        previous = value
        return previous, False
    else:
        current  = value + 10
        return current, True

a, was_current = check_val(3)

print(a, was_current)  # --> 3 False

Well, first of all, you can't do this directly. There is no way of telling which return sent you the value just from the value itself.

You can of course return a tuple, as pointed out within other answers.

In my oppinion though, you should try to decouple checks from other calculations if you are interested in both informations, for it makes it easier to understand the returned value.

Like that, maybe:

def check_condition(value):
    if value < 10:
        return True
    return False

def get_result(value, condition):
    if condition:
        return value
    else:        
        return value + 10

val = 5
check_result = check_condition(val)
result = get_result(val, check_result)

It's hard to say if that makes sense since I don't know your use case. In your particular example I'd probably stick to the tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM