Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet:
if target: with open(target, \'w\') as h
Another possible solution: do not try to avoid the context manager exit method, just duplicate stdout.
with (os.fdopen(os.dup(sys.stdout.fileno()), 'w') if target == '-' else open(target, 'w')) as f: f.write("Foo")