Python decorator gaining access to itself

Here is an example of a method that is inside a Python class:

def publish_aggregate_account_group_stats(self, account_group_token):
    message = {
        "type": "metrics-aggregate-account-group-stats",
        "accountGroupToken": account_group_token
    }
    try:
        self._get_writer().write(message)
    except:
        self._put_cache(message)

There are several methods in my class: all run try/except, which I think can be DRYed or cleared by simply creating a decorator that handles this for me. I'm just not sure how the decorator will look / work when referring to self.

+4
source share
1 answer

something like this will work:

from contextlib import contextmanager
class Test(object):
    def __init__(self):
        self.j = set()

    @contextmanager
    def handle_exc(self, msg):
        try:
            yield
        except:
            print('adding to internal structure:', msg)
            self.j.add(msg)

    def test(self):
        m = 'snth'
        with self.handle_exc(m):
            raise Exception('error')

the decorator is difficult to use here because you create the values ​​inside the function itself, so the external decorator will never know about them unless you find a way to distribute them (through some kind of exception or something similar).

+1

Source: https://habr.com/ru/post/1613233/


All Articles