Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python async special class methods __delete__

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...
like image 553
Julien Castiaux Avatar asked Feb 26 '26 06:02

Julien Castiaux


1 Answers

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
like image 181
Julien Castiaux Avatar answered Feb 28 '26 22:02

Julien Castiaux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!