弃用函数参数

Deprecate a function parameter

有时我们需要使用装饰器将函数参数标记为已弃用。

例如:

@deprecated_param(version="0.2.3",
                  reason="you may consider using *styles* instead.",
                  deprecated_args='color background_color')
def paragraph(text, color=None, background_color=None, styles=None):
    styles = styles or {}
    if color:
        styles['color'] = color
    if background_color:
        styles['background-color'] = background_color
    html_styles = " ".join("{k}: {v};".format(k=k, v=v) for k, v in styles.items())
    html_text = xml.sax.saxutils.escape(text)
    return ('<p styles="{html_styles}">{html_text}</p>'
            .format(html_styles=html_styles, html_text=html_text))

https://github.com/tantale/deprecated/issues/8

我正在寻找实现它的好方法。

Python 标准库或著名开源项目(如 Flask、Django、setuptools...)中是否有任何代码示例?

您可以将 deprecated_args 拆分成一个集合,以便您可以使用集合交集来获取有问题的关键字参数:

class deprecated_param:
    def __init__(self, deprecated_args, version, reason):
        self.deprecated_args = set(deprecated_args.split())
        self.version = version
        self.reason = reason

    def __call__(self, callable):
        def wrapper(*args, **kwargs):
            found = self.deprecated_args.intersection(kwargs)
            if found:
                raise TypeError("Parameter(s) %s deprecated since version %s; %s" % (
                    ', '.join(map("'{}'".format, found)), self.version, self.reason))
            return callable(*args, **kwargs)
        return wrapper

这样:

@deprecated_param(version="0.2.3",
                  reason="you may consider using *styles* instead.",
                  deprecated_args='color background_color')
def paragraph(text, color=None, background_color=None, styles=None):
    pass

paragraph('test')
paragraph('test', color='blue', background_color='white')

输出:

TypeError: Parameter(s) 'color', 'background_color' deprecated since version 0.2.3; you may consider using *styles* instead.