Python 惯用的解包赋值或 False

发布于 2024-10-21 22:17:04 字数 267 浏览 5 评论 0原文

如果函数在成功时返回两个值列表或元组,在失败时返回 False,那么如何最好地将返回列表解压为两个变量,同时检查 False?

def get_key_value():
  if (cond != True):
    return False
  return [val1, val2]

# Call it
# How can I also check for False while unpacking?
key, value = get_key_value()

If function returns a two value list or tuple on success or False on failure, how can I best unpack the return list into two variables while also checking for False?

def get_key_value():
  if (cond != True):
    return False
  return [val1, val2]

# Call it
# How can I also check for False while unpacking?
key, value = get_key_value()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

青瓷清茶倾城歌 2024-10-28 22:17:04

将@Felix Kling 的精彩评论转化为答案。

如果无法找到(键,值)对表明存在某种系统故障,那么最好抛出异常。如果您的失败实际上并不属于任何标准异常,您应该构建一个您自己的新异常类型。

cond != True 最好写成 not cond。另外,如果没有必要,最好不要创建列表。

class DataNotFound(Exception): pass

def get_key_value():
  if not cond:
    raise DataNotFound("Couldn't find it!")
  return val1, val2

try:
    key,value = get_key_value()
except DataNotFound:
    #handle the failure somehow
    key, value = 'ERROR', 'ERROR'

Coverting @Felix Kling's great comment into an answer.

If not being able to find a (key, value) pair indicates some kind of system failure, it would be better to throw an exception. If your failure doesn't really fall into any of the standard exceptions, you should build a new exception type of your own.

The cond != True is better written as not cond. Also it's better to not create a list if it's not necessary.

class DataNotFound(Exception): pass

def get_key_value():
  if not cond:
    raise DataNotFound("Couldn't find it!")
  return val1, val2

try:
    key,value = get_key_value()
except DataNotFound:
    #handle the failure somehow
    key, value = 'ERROR', 'ERROR'
空气里的味道 2024-10-28 22:17:04

这属于 Python 的“请求宽恕比请求许可更容易”政策。我避免在函数中捕获 TypeError,以防出现其他不可预见的问题。

data = get_key_value()
try:
   key, value = data
except TypeError:
   #handle the failure somehow
   key, value = 'ERROR', 'ERROR'

This falls under the "Easier to Ask for Forgiveness than Permission" policy of Python. I avoid catching TypeError in your function, in case there's some other unforeseen problem.

data = get_key_value()
try:
   key, value = data
except TypeError:
   #handle the failure somehow
   key, value = 'ERROR', 'ERROR'
那片花海 2024-10-28 22:17:04

我不认为有一种惯用的方法可以做到这一点——尤其是因为以这种方式运行的函数本身就是不惯用的。如果你必须这样做,我建议你简单地利用你的 2 元素列表或元组是“真”值而不是“假”值这一事实(这不是 Python 术语,但它很有用)

pair_or_false = get_key_value()
if pair:
    key,value = val
else:
    # handle failure in whatever way

:另一种方法是将未找到的情况视为例外:

try:
    key,value = get_key_value()
except TypeError:
    # deal with not-found case

但是,如果除不成功的解包之外的任何其他情况都可能引发 TypeError,那么您就有可能以这种方式掩盖真正的错误。

I don't think there is an idiomatic way to do this -- not least because a function that behaves that way is itself unidiomatic. If you have to do it, I suggest you simply make use of the fact that your 2-element list or tuple is a "truthy" rather than a "falsy" value (this isn't Python terminology but it's useful):

pair_or_false = get_key_value()
if pair:
    key,value = val
else:
    # handle failure in whatever way

The obvious alternative is to treat the not-found case as an exception:

try:
    key,value = get_key_value()
except TypeError:
    # deal with not-found case

but if there's any possibility at all that something other than the unsuccessful unpacking could raise a TypeError then you run the risk of masking a genuine error that way.

静若繁花 2024-10-28 22:17:04

由于混合了返回类型,您遇到了问题。仅仅因为你可以,并不意味着你应该这样做。

尽管我同意这里其他人的观点,即例外是一种合适的方法,但这可能取决于您是否希望找到有效的密钥和密钥。大部分时间都看重。如果是这样,请使用异常(例如 KeyError)来指示该函数失败。但如果您预计它会以很高的速度失败,您可能不希望出现异常开销。在这种情况下,从 get_key_value 返回类似 [None, None] 的内容,然后您的调用代码将如下所示:

key, value = get_key_value()
if key:
    # take action
else:
    # handle the error appropriately

You're running into problems because you're mixing return types. Just because you can doesn't mean you should.

Although I agree with the others here that an exception is one appropriate way to go, it may depend on whether you expect to find a valid key & value most of the time. If so, use an exception (something like KeyError) to indicate that the function failed. But if you expect it to fail at a high rate, you may not want the exception overhead. In that case, return something like [None, None] from get_key_value and then your calling code would look like:

key, value = get_key_value()
if key:
    # take action
else:
    # handle the error appropriately
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文