What should replace comparisons with False in python?

偶尔善良 提交于 2019-12-24 02:24:11

问题


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 doesn't like this and reports Comparisons with False are not necessary and may not work as expected.

What's the python way for doing this?


回答1:


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

  • 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).

  • 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.

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




回答2:


Normally you would return None instead of False i.e. if an object doesn't match. And then check if my_var == None: as all not 0, not False and not None return True.




回答3:


If you just want to check for a falsy value:

myval = findit('something')
if not myval:
   "not found"

You don't want to do this if you could actually return a value for the "is-found" case which has a falsy value. E.g., if [] (empty list) is found, this will still report "not found".

If you care that it is actually False, use is. True, False, and None are singletons, so the identity comparison operator is used.

if myval is False:
   "not found"

In this case you are using False as a sentinel value to indicate that there is no result.

Usually None is used as a sentinel "no-value", however, so I suggest you change the signature of your function to return None if no value is found. This conforms better with Python idiom and the behavior of methods such as {}.get('missing-key').

myval = findit('something')
if myval is None:
    "not found"

In cases where no sentinel value is possible because any value could be returned (even None or False), Python uses an exception to signal that no value was found. E.g. {}['missing-key'] will raise KeyError.




回答4:


Usually you'd just use not:

if not my_var: continue



回答5:


Python is actually more strongly typed than C++ in this regard. Only genuine booleans can be True or False.

So my_var must be a boolean. Therefore you just check it as one.

if not my_var:
     continue


来源:https://stackoverflow.com/questions/15229215/what-should-replace-comparisons-with-false-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!