python的delete方法_python异步特殊类方法__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...

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值