Wrap in parentheses to avoid syntax errors with operators over many lines

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the functions category.

Last Updated: 2021-05-16

I was having trouble getting logical operators to work across multiple lines of python when I had split these lines up (in order to meet formatting expectations of 80 chars).

i.e. I wanted this to work:

instrumental_volume_ratio = accompaniment_volume_ratio *
  self.config["instrumental_volume"]

But instead it gave a syntax error...

The fix was to wrap the entire expression that straddled two lines in some parentheses.

        instrumental_volume_ratio = (accompaniment_volume_ratio *
                                     self.config["instrumental_volume"])

This tricks works in many other languages too.

Lesson

If splitting an operation over two lines causes syntax issues, wrap with parentheses.