设计一个装饰器,动态为函数添加或修改其文档字符串(docstring),并确保新的docstring符合PEP 257规范。

"""
设计一个装饰器,动态为函数添加或修改其文档字符串(docstring),并确保新的docstring符合PEP 257规范。

PEP 257规范对docstring的主要要求包括:
1. 单行docstring应简洁,用三引号包裹,且闭合引号与内容在同一行。
2. 多行docstring的第一行应为摘要行,之后空一行,再提供详细描述。
3. 所有docstring应使用英文。

以下是一个动态修改或添加docstring的装饰器实现,同时确保符合PEP 257规范:
"""

def update_docstring(new_doc):
    """
    装饰器函数,用于动态更新被装饰函数的docstring。

    :param new_doc: 新的docstring,需要符合PEP 257规范。
    :return: 装饰器函数。
    """
    def decorator(func):
        # 检查new_doc是否符合PEP 257规范
        if not isinstance(new_doc, str):
            raise ValueError("Docstring must be a string.")
        if not new_doc.strip():
            raise ValueError("Docstring cannot be empty.")

        # 更新函数的docstring
        func.__doc__ = new_doc
        return func
    return decorator


# 示例1:为没有docstring的函数添加docstring
@update_docstring("""Calculate the sum of two numbers.""")
def add(a, b):
    return a + b

print(add.__doc__)  # 输出: Calculate the sum of two numbers.


# 示例2:修改已有docstring的函数的docstring
@update_docstring(
    """
    Calculate the product of two numbers.

    Multiplies the two input numbers and returns the result.
    """
)
def multiply(a, b):
    """Old docstring."""
    return a * b

print(multiply.__doc__)
# 输出:
# Calculate the product of two numbers.
#
# Multiplies the two input numbers and returns the result.


# 示例3:触发异常,检查docstring是否为空
@update_docstring("")
def divide(a, b):
    return a / b
# 会抛出 ValueError: Docstring cannot be empty.


# 示例4:触发异常,检查docstring是否为字符串
@update_docstring(123)
def subtract(a, b):
    return a - b
# 会抛出 ValueError: Docstring must be a string.


"""
总结:
1. 装饰器update_docstring接受一个字符串参数new_doc,并返回一个装饰器函数decorator。
2. decorator会检查new_doc是否符合PEP 257规范,包括是否为字符串、是否非空。
3. 如果检查通过,decorator会动态修改被装饰函数的__doc__属性。
4. 示例中展示了如何为函数添加docstring、修改已有docstring,以及触发异常的情况。
"""