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.
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.
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.
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.
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.
In original if
statement you checking two conditions:
not foo in categories
- will be evaluated to True
if element foo
(str
, I guess) not presented in collection categories
not foo.capitalize() in categories
- will be evaluated to True
if capitalized element foo
not presented in collection categories
In modified if
statement you checking two completely different conditions:
not foo
- will be evaluated to True if foo
is empty, False
or None
foo.capitalize() in categories
- will be evaluated to True
if capitalized element foo
presented in collection categories
What you are doing is checking if foo
is False
and foo.capitalize()
is in categories.
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
EDIT: I give up. I’m on a phone. Can’t format. – Eli Kerrison-Male Oct 31 '17 at 07:17