Python and PEP8 - Recommendations on breaking up long lines?

Neil Cerutti mr.cerutti at
Thu Nov 28 04:09:53 CET 2013

tOn Wed, Nov 27, 2013 at 8:57 PM, Victor Hooi <victorhooi at> wrote:
>             with open(self.full_path, 'r') as input, open(self.output_csv, 'ab') as output:

There are two nice and clean solutions for this.

I usually nest them.

with open(self.full_path, 'r') as input:
  with open(self.ouptut_csv, 'ab') as output:

I use a non-standard (shortened) indentation for nested with
statements, to save space. I don't feel bad about this at all; the
with statement's syntax makes me do it!

Otherwise, contextlib.ExitStack is another way to separate them.

with contextlib.ExitStack() as stack:
    input = stack.enter_context(open(self.full_path, 'r'))
    writer = csv.writer(stack.enter_context(open(self.output_csv)))

When working with a csv file I like how it removes the output
temporary file object variable, though if you needed it for some
reason you could keep it.

Neil Cerutti

More information about the Python-list mailing list