Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pep8 minor annoyance

In /tmp/spam.py:

n = 69

if n == True:
    print 'potato'

pep8 utility complains about this conditional:

wim@SDFA100461C:/tmp$ pep8 spam.py 
spam.py:3:6: E712 comparison to True should be 'if cond is True:' or 'if cond:'
  • the first suggestion is wrong/"worse" according to pep8 itself
  • the second suggestion changes the behaviour of the code

What is the best practice for a case where you actually do want to check equality with True? Is identity checking with True using is OK? Why does pep8 utility offer an alternative which is explicitly discouraged in pep8 itself?

like image 622
wim Avatar asked Jan 09 '14 12:01

wim


People also ask

Is PEP8 deprecated?

Deprecated use of [pep8] section name in favor of [pycodestyle] ; #591.

Why is PEP8 line length so short?

PEP 8 suggests lines should be limited to 79 characters. This is because it allows you to have multiple files open next to one another, while also avoiding line wrapping. Of course, keeping statements to 79 characters or less is not always possible. PEP 8 outlines ways to allow statements to run over several lines.

What is PEP 8 and why is it important?

PEP 8 is a document that provides various guidelines to write the readable in Python. PEP 8 describes how the developer can write beautiful code. It was officially written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The main aim of PEP is to enhance the readability and consistency of code.


1 Answers

If you really do need to check equality with True then use == and ignore PEP8, but in almost any conceivable case that isn't what you want.

If you want to know whether the value you have is one of the values Python considers to be true, use if cond:. If you want to know whether the value you have is the singleton value True then use is True, the booleans True and False are singletons so it is correct to use is in this situation.

If you need to test whether your object is the singleton True, but a linter or a code reviewer complains about is True, then isinstance(x, bool) and x is a behaviorally equivalent (but slower) substitute.

Checking x == True is a halfway house. It is true when x is True is true, and false for your case of x=69, but there are other objects which are not themselves True but for which x==True gives an unexpectedly true result such as 1 == True being true. (thanks @Ant).

So putting that together:

value of n:    True  1     69     False   0
-----------------------------------------------
expression     result
-----------------------------------------------
if n:          True  True  True   False   False
if n is True:  True  False False  False   False
if n==True:    True  True  False  False   False

Pick the row from that table which gives the results you really wanted (and the last one isn't it).

like image 158
Duncan Avatar answered Nov 15 '22 06:11

Duncan