Skip to content

Instantly share code, notes, and snippets.

@leth
Forked from sloria/gist:5895687
Last active August 29, 2015 13:56
Show Gist options
  • Save leth/9291261 to your computer and use it in GitHub Desktop.
Save leth/9291261 to your computer and use it in GitHub Desktop.
f = open('file.txt', 'w')
f.write('hi')
f.close()
# Better
with open('file.txt', 'w') as f:
f.write('hi')
with pytest.raises(ValueError):
int('hi')
with connection(host, port) as socket:
socket.write(...)
from contextlib import contextmanager
@contextmanager
def connection(host, port):
sock = socket()
sock.connect((host, port))
try:
yield sock
finally:
sock.close()
with SomeProtocol(host, port) as protocol:
protocol.send(['get', signal])
result = protocol.receive()
class SomeProtocol:
def __init__(self, host, port):
self.host, self.port = host, port
def __enter__(self):
self._client = socket()
self._client.connect((self.host,
self.port))
def __exit__(self, exception, value, traceback):
self._client.close()
def send(self, payload): ...
def receive(self): ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment