Skip to content

Instantly share code, notes, and snippets.

@matteoferla
Last active February 9, 2022 13:24
Show Gist options
  • Save matteoferla/64b970cca20584c079c3bd5b90dc78c8 to your computer and use it in GitHub Desktop.
Save matteoferla/64b970cca20584c079c3bd5b90dc78c8 to your computer and use it in GitHub Desktop.
# "pseudo"-bound decorator within a class, with the class attribute boolean `prevent_error`.
# it does not inherit self and is not a classmethod or a static method. But will behave like one.
# it is a generator function, whose inner function is a normal bound
# Do note the print requires customisation, i.e. `self.descriptive_attribute`.
def failsafe(func):
def wrapper(self, *args, **kargs):
# the call happned after chekcing if it should croak on error so to make the traceback cleaner.
if self.prevent_error:
try:
return func(self, *args, **kargs)
except Exception as error:
print('Error caught in bound method `FOO().{n}` while parsing {g} ({a, k}): {e}'.format(n=func.__name__,
g=self.descriptive_attribute,
a=args,
k=kargs,
e=error))
return None
else:
return func(self, *args, **kargs)
return wrapper
@matteoferla
Copy link
Author

This is just a technical note that I am tempted to delete this as it's misleading: Adding a decorator to a method as opposed to a function is doable if self is passed, but it is rather silly.

Primarily because say one wanted a record of the error (eg. in this decorator) and used a class with call then it gets overly messy as opposed to simply having a dedicated sister method that acts a faux decorator and stores the details in the class instance attributes as opposed to as attributes of the decorator class instance which takes the place of the method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment