源碼:
def ensure_one(self):
""" Verifies that the current recorset holds a single record. Raises
an exception otherwise.
"""
try:
# unpack to ensure there is only one value is faster than len when true and
# has a significant impact as this check is largely called
_id, = self._ids # 開始沒明白什么意思,應該是python的多重賦值,只不過這種寫法的情況下等號右邊必須是可迭代的
return self
except ValueError:
raise ValueError("Expected singleton: %s" % self)
這段代碼如果換種方式就很好理解了:
def ensure_one(self): """
換種寫法 """ if len(self) == 1:
return self
else: raise ValueError("Expected singleton: %s" % self)