Refactor: Replace try/except with contextlib.suppress() #2991
-
DescriptionWhen the sole purpose is to suppress specific exceptions without any additional error handling logic, Python's standard library provides a more elegant solution: Benefits
Refactor ExampleCurrent Implementationclass WebSocket(HTTPConnection):
# ... other methods ...
async def iter_text(self) -> AsyncIterator[str]:
try:
while True:
yield await self.receive_text()
except WebSocketDisconnect:
pass
async def iter_bytes(self) -> AsyncIterator[bytes]:
try:
while True:
yield await self.receive_bytes()
except WebSocketDisconnect:
pass
async def iter_json(self) -> AsyncIterator[Any]:
try:
while True:
yield await self.receive_json()
except WebSocketDisconnect:
pass
# ... other methods ... Proposed Implementationimport contextlib
class WebSocket(HTTPConnection):
# ... other methods ...
async def iter_text(self) -> AsyncIterator[str]:
with contextlib.suppress(WebSocketDisconnect):
while True:
yield await self.receive_text()
async def iter_bytes(self) -> AsyncIterator[bytes]:
with contextlib.suppress(WebSocketDisconnect):
while True:
yield await self.receive_bytes()
async def iter_json(self) -> AsyncIterator[Any]:
with contextlib.suppress(WebSocketDisconnect):
while True:
yield await self.receive_json()
# ... other methods ... This refactoring aligns with modern Python idioms and makes the codebase more concise while maintaining the same functionality. The use of What are your thoughts on this proposed refactoring? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
They don't bring much, and pollute the history. |
Beta Was this translation helpful? Give feedback.
Understood, thanks for the feedback!