RM1970 RM1970 - 3 months ago 7
Python Question

Syntax error when there's a newline after an or operator

This is OK:

if 'something' in data['meta']:
<do something>


This is a syntax error. Why?

if ('something' in data['meta']) or
('something_else' in data['meta']):
<do something>


The interpreter hands this out:

File "test.py", line 1
if ('something' in data['meta']) or
^
SyntaxError: invalid syntax

Answer

Newlines are important. Python needs to know how to parse things. For the second code snippet, you are separating the if into two lines, and Python doesn't like that since it looks like a separate command. Two common ways to span multiple lines is using a backslash or parentheses. For example, both of these are valid syntax:

if ('something' in data['meta']) or \
       ('something_else' in data['meta']):
    <do something>

if (('something' in data['meta']) or
       ('something_else' in data['meta'])):
    <do something>

You can read about this more in the PEP 8 Style Guide.

Small Note: I add extra indentation on multi-line if statements to easily distinguish when the condition ends and when the subsequent code begins. It's just preference, and PEP8 provides options here.