Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deprecate a function parameter

Sometimes we need to mark a function parameter as deprecated, using a decorator.

For instance:

@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))

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

I'm searching a good way to implement that.

Do you now any code examples in the Python Standard library or in famous open source projects (like Flask, Django, setuptools...)?

like image 490
Laurent LAPORTE Avatar asked Mar 07 '26 08:03

Laurent LAPORTE


1 Answers

You can split deprecated_args into a set so that you can use set intersection to obtain the offending keyword arguments:

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

so that:

@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')

outputs:

TypeError: Parameter(s) 'color', 'background_color' deprecated since version 0.2.3; you may consider using *styles* instead.
like image 124
blhsing Avatar answered Mar 08 '26 20:03

blhsing