python - Can a "with" statement be used conditionally? -
i have python function of following structure, computes results , writes them file:
results = [] open(filename, "w") output: item in items: result = compute_stuff(item) write_result(item, result, output) results.append(result) return results
now don't want write results file - want compute them , have them returned. making "write_result" conditional easy, there way make file creation in "with" statement condition-dependent? (i know handle opening , closing of file explicitly, incur "try/finally" overhead "with" statement created avoid.)
is there elegant solution this?
edited add: may have oversimplified example. instead of writing arbitrary file, i'm using matplotlib.backends.backend_pdf.pdfpages
(link), , adding plot (new page in pdf) in every step. in particular, means cannot re-open pdf file pdfpages
, because overwritten.
you can write own context manager function:
class dummysink(object): def write(self, data): pass # ignore data def __enter__(self): return self def __exit__(*x): pass def datasink(filename): if filename: return open(filename, "w") else: return dummysink() ... results = [] datasink(filename) output: item in items: result = compute_stuff(item) write_result(item, result, output) results.append(result) return results
Comments
Post a Comment