弃用函数参数

问题描述 投票:0回答:1

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

例如:

@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 ......)中有任何代码示例吗?

python deprecated
1个回答
0
投票

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

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.
© www.soinside.com 2019 - 2024. All rights reserved.