blhsing
(Ben Hsing)
December 16, 2025, 8:13am
60
It’s quite common for a function to create an object and modify the object in some ways before returning the object, e.g.:
self.update(other)
return self
def __or__(self, other):
if isinstance(other, _collections_abc.Mapping):
c = self.copy()
c.update(other)
return c
return NotImplemented
def __ror__(self, other):
if isinstance(other, _collections_abc.Mapping):
c = self.__class__()
c.update(other)
c.update(self)
return c
return NotImplemented
class KeyedRef(ref):
"""Specialized reference that includes a key corresponding to the value.
which, with the syntax I suggested above, can be rewritten as:
def __ror__(self, other):
if isinstance(other, _collections_abc.Mapping):
return self.__class__(){.update(other), .update(self)}
return NotImplemented
An object can also go through various validations before proceeding with the main task:
def readinto(self, b):
self._check_not_closed()
self._check_read("readinto")
return self._buffer.readinto(b)
def readinto1(self, b):
self._check_not_closed()
self._check_read("readinto1")
return self._buffer.readinto1(b)
def peek(self, n):
self._check_not_closed()
self._check_read("peek")
return self._buffer.peek(n)
@property
def closed(self):
return self.fileobj is None
def close(self):
fileobj = self.fileobj
which can be rewritten as:
def peek(self, n):
return self{._check_not_closed(), ._check_read("peek")}._buffer.peek(n)
Like the walrus operator, this is a quality-of-life improvement that, while yes, one can certainly live without, can make such common patterns of codes handier to write.
4 Likes