[英]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? 我怎么知道是
current
还是previous
?
You can have your function return a tuple
with the necessary meta and unpack via sequence unpacking: 您可以让函数返回带有必要meta的
tuple
,并通过序列拆包进行拆包:
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.
在您的特定示例中,我可能会坚持使用元组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.