Created
January 25, 2022 12:59
-
-
Save terenty-rezman/5d034984aa16cd1463296b9ddfe13a24 to your computer and use it in GitHub Desktop.
Python class decorate own methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def for_all_own_methods(decorator: Callable): | |
""" | |
class decorator | |
apply decorator function to all class methods, excluding inherited ones | |
Args: | |
decorator ([Callable]): decorator function to apply to all own methods | |
""" | |
def decorate(cls): | |
import inspect | |
# get a list of inherited methods | |
mro = inspect.getmro(cls) | |
if len(mro) > 1: | |
inherited_methods = inspect.getmembers(mro[1], predicate=inspect.ismethod) | |
else: | |
inherited_methods = {} | |
# build a set of inherited methods | |
inherited_methods = { name for name, _ in inherited_methods} | |
# for all methods in class | |
for name, method in inspect.getmembers(cls, predicate=inspect.ismethod): | |
# skip all speciall methods | |
if name.startswith("_"): | |
continue | |
# skip inherited methods | |
elif name in inherited_methods: | |
continue | |
else: | |
# apply retry decorator to own methods | |
setattr(cls, name, decorator(method)) | |
return cls | |
return decorate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment