This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author bup
Recipients Jim Fasarakis-Hilliard, benjamin.peterson, bup, josh.r, martin.panter, ncoghlan, xiang.zhang
Date 2017-04-09.04:02:25
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1491710547.3.0.731608782899.issue29944@psf.upfronthosting.co.za>
In-reply-to
Content
Just wanted to add that I found this when I was trying to find a way to decorate all methods in a class without using a metaclass or modifying __getattr__.


Using Josh's workaround, here's a simple demonstration that (at least at first glance) prints a message when a method is called and when it is finished:

def mydec(*, enter=True, exit=True):
    def make_closure(__class__):
        return (lambda: super).__closure__
    def outer(cls):
        def wrapper(method):
            @functools.wraps(method)
            def inner(*args, **kwargs):
                if enter:
                    print('entering', method.__qualname__)
                r = method(*args, **kwargs)
                if exit:
                    print('exiting', method.__qualname__)
                return method(*args, **kwargs)
            return inner    
        for name, value in cls.__dict__.items():
            if isinstance(value, types.FunctionType):
                method = types.FunctionType(getattr(cls, name).__code__,
                                            globals(),
                                            closure=make_closure(cls))
                setattr(cls, name, wrapper(method))
        return cls
    return outer
History
Date User Action Args
2017-04-09 04:02:27bupsetrecipients: + bup, ncoghlan, benjamin.peterson, martin.panter, josh.r, xiang.zhang, Jim Fasarakis-Hilliard
2017-04-09 04:02:27bupsetmessageid: <1491710547.3.0.731608782899.issue29944@psf.upfronthosting.co.za>
2017-04-09 04:02:27buplinkissue29944 messages
2017-04-09 04:02:26bupcreate