class-based class decorator

Albert-Jan Roskam fomcl at yahoo.com
Fri Jan 9 16:26:52 EST 2015



Hi,

I am trying to write a class decorator that checks whether deprecated parameters with non-default

arguments are used. More complete code is here: http://pastebin.com/ZqnMis6M. In the code below, 

how should I modify __call__ such that f.bar(old="oh no") prints "hello world"?
I thought it would be a fun way to play with the inspect module, but my head is numb now and I am thirsty for a beer!



import inspectimport functools
import warnings


class check_deprecated_args(object):
    
    """
    Class decorator that checks whether deprecated parameters with non-default
    arguments are used


    Parameters
    ----------
    deprecated_params : tuple
        tuple of strings of parameters that should raise a DeprecationWarning,
        if they are used with non-default arguments

    Raises
    ------
    DeprecationWarning : if deprecated parameters are used with 
        non-default arguments in the class's constructor.
    """

    def __init__(self, deprecated_params):
        self.deprecated_params = deprecated_params

    def __call__(self, cls):
        @functools.wraps(cls)
        def inner(*used_args, **used_kwargs):
            print "called"  
            # insert sneaky 'inspect' code here
            #pprint( dict(inspect.getmembers(cls)) )
            return cls  # --- this is wrong, it should return the Foo instance object!
        return inner

if __name__ == "__main__":
    @check_deprecated_args(deprecated_params=("old", "older"))
    class Foo(object):
        def __init__(self, old=True, older=None, new="yaay"):
            pass
        def bar(self, old=True, new=True):
            print "hello world"

    f = Foo(new="great", old="obsolete", older="stop using it")
    print repr(f)
    print f.bar(old="oh no")

 
Regards,

Albert-Jan




~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 

fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 



More information about the Python-list mailing list