1

I attempt to refactor the compound conditions

if not foo in categories and not foo.capitalize() in categories:

to codes like

if not foo and foo.capitalize() in categories:

It did not work.

4 Answers4

4

So you’re aware that this works:

if not foo in categories and not foo.capitalize() in categories:

It parses as (not (foo in categories)) and (not (foo.capitalize() in categories), i.e.

  • foo is not in categories, and
  • foo.capitalize() is not in categories.

Since parsing always works the same way and doesn’t guess what you’re most likely to mean, your revised statement

if not foo and foo.capitalize() in categories:

is parsed as (not foo) and (foo.capitalize() in categories), i.e.

  • foo is not, and
  • foo.capitalize() is in categories

A cleaner way to write this in Python is with x not in y instead of not x in y (they’re equivalent):

if foo not in categories and foo.capitalize() not in categories:

but as far as expressing “neither of these” in a short way here… there’s not much beyond set operators:

if not {foo, foo.capitalize()}.intersection(categories):

shorthand if categories is also a set:

if not {foo, foo.capitalize()} & categories:

Notice how it’s not much shorter and how it is harder to understand.

Ry-
  • 218,210
  • 55
  • 464
  • 476
1

In original if statement you checking two conditions:

  1. not foo in categories - will be evaluated to True if element foo (str, I guess) not presented in collection categories
  2. not foo.capitalize() in categories - will be evaluated to True if capitalized element foonot presented in collection categories

In modified if statement you checking two completely different conditions:

  1. not foo - will be evaluated to True if foo is empty, False or None
  2. foo.capitalize() in categories - will be evaluated to True if capitalized element foo presented in collection categories
kvorobiev
  • 5,012
  • 4
  • 29
  • 35
0

What you are doing is checking if foo is False and foo.capitalize() is in categories.

Mitiku
  • 5,337
  • 3
  • 18
  • 35
0

If you have specific all and / not / or cases as you mentioned above, I generally go around with this way:

if not all( [foo in categories, foo.capitalize() in categories] ):

It makes readability easy and debugging simple too

see this thread for example

NoobEditor
  • 15,563
  • 19
  • 81
  • 112