文档字符串和类型提示

文档字符串和类型提示

原则

  1. 文档字符串说明操作或使用方法而不是解释理由
  2. 文档字符串是文档而不是注释
  3. 在代码中添加注释不是一个好的实践
    • 注释表示未能在代码中准确表达想法。如果必解释原因或实现步骤,那证明代码不够好。
    • 注释可能产生误导。修改代码往往忘记更新注释,过时的注释和现有代码的逻辑常常令人感到困惑。
  4. 极少数情况下,无法避免注释,这种情况下可以接受描述性的注释。
  5. 多写文档字符串,少写注释。

示例

class MyDict(dict):
    def update(self, E=None, **F):
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        
        >>> d = MyDict()
        >>> d.update({1: "one", 2: "two"})
        >>> d
        {1: "one", 2: "two"}
        >>> d.update([(3, "three"), (4, "four")])
        >>> d
        {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
        """
        super().update()

文档字符串会存储在对象的__doc__属性中

def my_function():
    """
    Run some computation
    """
    return None

print(my_function.__doc__)
# 'Run some computation'

Python3中引入了类型提示

class Point:
    def __init__(self, lat, long):
        self.lat = lat
        self.long = long

def locate(latitude: float, longitude: float) -> Point:
    """
    Find an object in the map by its coordinates
    """
    return Point(latitude, longitude)

print(locate.__annotations__)
# {'latitude': , 'longitude': , 'return': }

class Point:
    lat: float
    long: float

print(Point.__annotations__)
# {'lat': , 'long': }

文档字符串和类型提示结合

def data_from_response(response: dict) -> dict:
    """
    If the response is OK, return its payload.
    - response: a dict like:
    {
        "status": 200, # 
        "timestamp": "....", # ISO format string of the current date time
        "payload": { ... } # dict with the returned data
    }
    - Returns a dict like:
    {
        "data": { ... } 
    }
    - Raises:
        - ValueError if the HTTP status is != 200
    """
    if response["status"] != 200:
        raise ValueError
    return {"data": response["payload"]}

详细了解类型提示请查看mypy

你可能感兴趣的:(文档字符串和类型提示)