在python中应该用False代替比较的内容是什么? [英] What should replace comparisons with False in python?

查看:197
本文介绍了在python中应该用False代替比较的内容是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,如果未找到内容,则返回False,并返回具有我正在寻找的内容的数据结构.当我将此函数返回的值分配给for循环中的变量my_var时,我将执行if my_var == False: continue进行操作.

I have a function that returns False if something isn't found, and returns a data structure with what I'm looking for otherwise. When I assign the value returned from this function to a variable my_var in a for loop, I do a if my_var == False: continue to carry on.

pychecker不喜欢这样,并报告Comparisons with False are not necessary and may not work as expected.

pychecker doesn't like this and reports Comparisons with False are not necessary and may not work as expected.

执行此操作的python方法是什么?

What's the python way for doing this?

推荐答案

作为表明没有结果的返回值,None几乎总是更好.

As a return value indicating absence of a result, None is almost always better.

  • 如果必须使用False,请使用not my_var.假定非-False返回值从不假"(bool()将其转换为False-空字符串,空集合和其他一些情况就是这种情况).

  • If you must use False, use not my_var. This assumes non - False return values are never "falsy" (bool() converts it into False - this is the case for empty strings, empty collections, and a few other things).

如果对象可能是虚假的,但必须与False区分开,则必须进行比较,并且您必须忽略该错误(较小的变化,my_var is False会更惯用,但这是几乎一样).但这不是一个很好的情况,您应该避免这种情况,以免弄清楚.

If objects may be falsy but must be distinguished from False, then the comparison is necessary and you'll have to ignore the error (a minor variation, my_var is False would be slightly more idiomatic, but it's virtually the same). But that's not a nice situation to be in and you should avoid it for the fake of clarity.

要重复一次:如果可能,请使用None并测试my_var is None.

To repeat myself: If at all possible, use None and test for my_var is None.

这篇关于在python中应该用False代替比较的内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆