Skip to content

Instantly share code, notes, and snippets.

@addam
Last active December 11, 2019 08:48
Show Gist options
  • Save addam/3e77e40e5c77167d253473dea418fcdd to your computer and use it in GitHub Desktop.
Save addam/3e77e40e5c77167d253473dea418fcdd to your computer and use it in GitHub Desktop.
simplify repeated calls to `print(..., file=f)` in Python
from functools import partial
class printer:
def __init__(self, *args):
self.args = args
def __enter__(self):
self.f = open(*self.args)
return partial(print, file=self.f)
def __exit__(self, *args):
self.f.__exit__(*args)
with printer("out.txt", "w+") as p:
p("Hello, world!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment