2

Which is more preferred below? and why?

Does PEP8 have a say in this?

if retcode != 0 and not "ignore_warning" in cmd_out:

or

if retcode != 0 and "ignore_warning" not in cmd_out:

functionally, i believe they achieve the same

ealeon
  • 12,074
  • 24
  • 92
  • 173

2 Answers2

3

Use "is not" operator rather than "not ... is" . While both expressions are functionally identical, the former is more readable and preferred.

PEP8

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
yyforbidden
  • 159
  • 8
  • 2
    This has nothing to do with the `in` operator though. – Selcuk Dec 05 '19 at 01:38
  • Why it should be about `in`? – Marcin Orlowski Dec 05 '19 at 01:40
  • 1
    @MarcinOrlowski because the original question is asking about `in` – user1558604 Dec 05 '19 at 01:43
  • @MarcinOrlowski I believe the point in this is about to make it more readable when using "not", regardless if it is used with "in" or "is". I found this answer as well, which explains more than I thought. https://stackoverflow.com/questions/17659303/what-is-more-pythonic-for-not – yyforbidden Dec 05 '19 at 01:46
  • 2
    The information you quoted is specifically about `is not` and not about the placement of `not` in general. – Selcuk Dec 05 '19 at 02:01
  • We can agree that PEP-8 is talking about `... is not ...`/`not ... is...`. But, is there anything about the *reason* given to prefer `is not` that doesn't apply to `not in` as well? – chepner Dec 05 '19 at 03:45
3

Looking at the disassembled bytecode both the expressions are the same. From readability point of view second option is better.

if a != 10 and not b in "test":

and

if a != 10 and b not in "test":

gives the same disassembled code

  2           0 LOAD_FAST                0 (a)
              2 LOAD_CONST               1 (10)
              4 COMPARE_OP               3 (!=)
              6 POP_JUMP_IF_FALSE       26
              8 LOAD_FAST                1 (b)
             10 LOAD_CONST               2 ('test')
             12 COMPARE_OP               7 (not in)
             14 POP_JUMP_IF_FALSE       26
abhilb
  • 5,639
  • 2
  • 20
  • 26