Message291349
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 |
|
Date |
User |
Action |
Args |
2017-04-09 04:02:27 | bup | set | recipients:
+ bup, ncoghlan, benjamin.peterson, martin.panter, josh.r, xiang.zhang, Jim Fasarakis-Hilliard |
2017-04-09 04:02:27 | bup | set | messageid: <1491710547.3.0.731608782899.issue29944@psf.upfronthosting.co.za> |
2017-04-09 04:02:27 | bup | link | issue29944 messages |
2017-04-09 04:02:26 | bup | create | |
|