semicolon at end of python's statements
Neil Cerutti
neilc at norwich.edu
Tue Sep 3 16:00:47 EDT 2013
On 2013-09-03, Neil Cerutti <neilc at norwich.edu> wrote:
> 3.2 and above provide contextlib.ExitStack, which I just now
> learned about.
>
> with contextlib.ExitStack() as stack:
> _in = stack.enter_context(open('some_file'))
> _out = stack.enter_context(open('another_file', 'w'))
>
> It ain't beautiful, but it unfolds the nesting and gets rid of
> the with statement's line-wrap problems.
It just occurred to me that in most of my use cases ExitStack
saves me from coming up with a name for the file objects at all,
since they are needed only to make csv objects.
Here's a csv file transformer pattern:
import contextlib
import csv
import transform
with contextlib.ExitStack() as stack:
reader = csv.DictReader(stack.enter_context(open('some_file', newline='')))
writer = csv.DictWriter(
stack.enter_context(open('another_file', 'w', newline='')),
fieldnames=reader.fieldnames)
writer.writeheader()
for record in reader:
writer.writerow(transform.transform(record))
Too bad it's so dense looking.
--
Neil Cerutti
More information about the Python-list
mailing list