【发布时间】:2021-09-01 14:40:42
【问题描述】:
在 Google 的 Python 样式指南文档中,他们提到了以下内容:
请注意,文档中没有提到 ValueError 的提升 字符串的“Raises:”部分,因为它不适合保证 这种对 API 滥用的特定行为反应。
为什么不合适?这是否意味着一开始就不应该像这样使用 ValueError ?
def connect_to_next_port(self, minimum: int) -> int:
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
if minimum < 1024:
# Note that this raising of ValueError is not mentioned in the doc
# string's "Raises:" section because it is not appropriate to
# guarantee this specific behavioral reaction to API misuse.
raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
port = self._find_next_open_port(minimum)
if not port:
raise ConnectionError(
f'Could not connect to service on port {minimum} or higher.')
assert port >= minimum, (
f'Unexpected port {port} when minimum was {minimum}.')
return port
【问题讨论】:
-
如果你想防止错误的值,你可以作为你的函数的作者做任何你想做的事情,只要它被记录在案。您可以很好地选择返回
None或负值,让调用者决定在这种情况下该怎么做。但是恕我直言,最好(a)询问该代码的作者是否想确定他在这种特定情况下的意思(b)以基于意见的方式结束此问题