3

Strait to the point:

How can I async def specials class methods like __delete__ in python ?

Why I need this:

In order to implement a nice caching system shared between multiple process, I want to retrieve the data from the database once and store them in a cache, modify the data in the cache and when the data is not used anymore: update the database. My problem is, in order to know which instance is the last one, I want to use the __delete__ special method asyncly

def asyncinit(cls):
    """Credits: http://stackoverflow.com/a/33140788/4241798"""
    __new__ = cls.__new__

    async def init(obj, *arg, **kwarg):
        await obj.__init__(*arg, **kwarg)
        return obj

    def new(cls, *arg, **kwarg):
        obj = __new__(cls, *arg, **kwarg)
        coro = init(obj, *arg, **kwarg)
        return coro

    cls.__new__ = new
    return cls

@asyncinit
class AsyncUser:
    async def __init__(self, id: int):
        self.id = id
        with await cachepool as cache:
            cache.hincr(f"users:{id}", "refcnt")

    async def __delete__(self):
        """Won't work"""
        with await cachepool as cache:
            refcnt = await cache.hincrby(f"users:{self.id}", "refcnt", -1)
            if refcnt == 0:
                # update database

    # rest of the class...
Julien Castiaux
  • 96
  • 1
  • 11

1 Answers1

3

It is impossible to async def python's builint methods but it is possible to schedule a coroutine call outside the loop using loop.create_future or asyncio.ensure_future

class asyncdel:
    def __delete__(self):
        asyncio.ensure_future(free(self.__dict__.copy()))

async def free(data):
    pass
Julien Castiaux
  • 96
  • 1
  • 11