2

Consider this code:

if (something1 is not None and
    check_property(something_else) and
    dr_jekyll is mr_hyde):
    do_something(*args)
    other_statements()

It is obviously hard to tell where the predicate ends and the statements of the body begin, despite the code being written in PEP-8 manner.

We have devised two variants:

if ((something1 is not None) and
    (check_property(something_else)) and
    (dr_jekyll is mr_hyde)):
    do_something(*args)
    other_statements()

which is ugly and

if (something1 is not None and
        check_property(something_else) and
        dr_jekyll is mr_hyde):
    do_something(*args)
    other_statements()

which is also ugly.

I personally prefer #1, and my colleague uses #2. Is there a non-ugly and PEP-8 compliant canonical solution which improves readability over the approaches listed above?

Mischa Arefiev
  • 5,227
  • 4
  • 26
  • 34

2 Answers2

3

Change your if statement, using all():

if all([something1 is not None, 
        check_property(something_else), 
        dr_jekyll is mr_hyde]):
    #do stuff...
Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31
  • This is more Pythonic – shad0w_wa1k3r Nov 14 '13 at 15:27
  • 1
    This is not equivalent to having the «raw» `if` statement, e. g. conditions such as `if name is not None and len(name) > 5`, which are very common, cannot be converted. – Mischa Arefiev Nov 14 '13 at 15:30
  • all([1 is not None, len(range(3))>1]) -> True – Alexander Zhukov Nov 14 '13 at 15:33
  • `name = None` then `all([name is not None, len(name) > 5])`? – Mischa Arefiev Nov 14 '13 at 15:35
  • 4
    Note that if `something1` **is** `None`, then `check_property()` will not be called. Your expression, however, **will** call `check_property()` (all expressions are evaluated) before returning `True` or `False`. This is an important distinction; `and` and `or` short-circuit, letting you use them to guard against exceptions. – Martijn Pieters Nov 14 '13 at 15:37
  • See http://stackoverflow.com/questions/19913290/python-if-versus-and-function-execution-order and http://stackoverflow.com/questions/16069517/python-logical-evaluation-order-in-if-statement for more discussion on that. – Martijn Pieters Nov 14 '13 at 15:44
-1

Depending on your context, you might not need is not None

>>> a = [1]
>>> if a:
        print "hello, world"


hello, world
>>> if a is not None:
        print "hello, world"


hello, world
>>> 
C.B.
  • 8,096
  • 5
  • 20
  • 34