1
0
mirror of https://github.com/kevin1024/vcrpy.git synced 2025-12-08 16:53:23 +00:00

Automatically decorate dynamically added methods with auto_decorate

This commit is contained in:
Ivan Malison
2015-08-28 02:03:50 -07:00
parent 6fd04f3675
commit c8180326ad
2 changed files with 25 additions and 4 deletions

View File

@@ -98,13 +98,24 @@ def auto_decorate(
decorator,
predicate=lambda name, value: isinstance(value, types.FunctionType)
):
def maybe_decorate(attribute, value):
if predicate(attribute, value):
value = decorator(value)
return value
class DecorateAll(type):
def __setattr__(cls, attribute, value):
return super(DecorateAll, cls).__setattr__(
attribute, maybe_decorate(attribute, value)
)
def __new__(cls, name, bases, attributes_dict):
for attribute, value in attributes_dict.items():
if predicate(attribute, value):
attributes_dict[attribute] = decorator(value)
new_attributes_dict = dict(
(attribute, maybe_decorate(attribute, value))
for attribute, value in attributes_dict.items()
)
return super(DecorateAll, cls).__new__(
cls, name, bases, attributes_dict
cls, name, bases, new_attributes_dict
)
return DecorateAll