This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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