ura*_*ash 62 python python-3.x python-asyncio
如何await
在构造函数或类体中定义类?
例如我想要的:
import asyncio
# some code
class Foo(object):
async def __init__(self, settings):
self.settings = settings
self.pool = await create_pool(dsn)
foo = Foo(settings)
# it raises:
# TypeError: __init__() should return None, not 'coroutine'
Run Code Online (Sandbox Code Playgroud)
或者类body属性的示例:
class Foo(object):
self.pool = await create_pool(dsn) # Sure it raises syntax Error
def __init__(self, settings):
self.settings = settings
foo = Foo(settings)
Run Code Online (Sandbox Code Playgroud)
我的解决方案(但我希望看到更优雅的方式)
class Foo(object):
def __init__(self, settings):
self.settings = settings
async def init(self):
self.pool = await create_pool(dsn)
foo = Foo(settings)
await foo.init()
Run Code Online (Sandbox Code Playgroud)
dan*_*ano 81
大多数魔术方法设计没有工作async def
/ await
-在一般情况下,你应该只使用await
专用异步魔术方法里面- ,__aiter__
,__anext__
,__aenter__
和__aexit__
.在其他魔法方法中使用它或者根本不起作用(就像这样__init__
),或者会强制你总是在异步上下文中使用魔术方法调用的任何触发器.
现有的asyncio
库倾向于通过以下两种方式之一来处理这个问题:首先,我已经看到了使用的工厂模式(asyncio-redis
例如):
import asyncio
dsn = "..."
class Foo(object):
@classmethod
async def create(cls, settings):
self = Foo()
self.settings = settings
self.pool = await create_pool(dsn)
return self
async def main(settings):
settings = "..."
foo = await Foo.create(settings)
Run Code Online (Sandbox Code Playgroud)
其他库使用创建对象的顶级协同程序函数,而不是工厂方法:
import asyncio
dsn = "..."
async def create_foo(settings):
foo = Foo(settings)
await foo._init()
return foo
class Foo(object):
def __init__(self, settings):
self.settings = settings
async def _init(self):
self.pool = await create_pool(dsn)
async def main():
settings = "..."
foo = await create_foo(settings)
Run Code Online (Sandbox Code Playgroud)
您要调用的create_pool
函数实际上是使用此精确模式.aiopg
__init__
这至少解决了这个__init__
问题.我还没有看到可以在野外进行异步调用的类变量,所以我不知道已经出现了任何完善的模式.
kha*_*hyk 23
换句话的另一种方法是:
class aobject(object):
"""Inheriting this class allows you to define an async __init__.
So you can create objects by doing something like `await MyClass(params)`
"""
async def __new__(cls, *a, **kw):
instance = super().__new__(cls)
await instance.__init__(*a, **kw)
return instance
async def __init__(self):
pass
#With non async super classes
class A:
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
self.b = 2
super().__init__()
class C(B, aobject):
async def __init__(self):
super().__init__()
self.c=3
#With async super classes
class D(aobject):
async def __init__(self, a):
self.a = a
class E(D):
async def __init__(self):
self.b = 2
await super().__init__(1)
# Overriding __new__
class F(aobject):
async def __new__(cls):
print(cls)
return await super().__new__(cls)
async def __init__(self):
await asyncio.sleep(1)
self.f = 6
loop = asyncio.get_event_loop()
e = loop.run_until_complete(E())
e.b # 2
e.a # 1
c = loop.run_until_complete(C())
c.a # 1
c.b # 2
c.c # 3
f = loop.run_until_complete(F()) # Prints F class
f.f # 6
Run Code Online (Sandbox Code Playgroud)
Hua*_*Gao 18
我会推荐一个单独的工厂方法.这是安全和直接的.但是,如果你坚持使用的async
版本__init__()
,这是一个例子:
def asyncinit(cls):
__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)
#coro.__init__ = lambda *_1, **_2: None
return coro
cls.__new__ = new
return cls
Run Code Online (Sandbox Code Playgroud)
用法:
@asyncinit
class Foo(object):
def __new__(cls):
'''Do nothing. Just for test purpose.'''
print(cls)
return super().__new__(cls)
async def __init__(self):
self.initialized = True
Run Code Online (Sandbox Code Playgroud)
async def f():
print((await Foo()).initialized)
loop = asyncio.get_event_loop()
loop.run_until_complete(f())
Run Code Online (Sandbox Code Playgroud)
输出:
<class '__main__.Foo'>
True
Run Code Online (Sandbox Code Playgroud)
说明:
您的类构造必须返回一个coroutine
对象而不是它自己的实例.
小智 15
更好的是你可以做这样的事情,这很容易:
import asyncio
class Foo:
def __init__(self, settings):
self.settings = settings
async def async_init(self):
await create_pool(dsn)
def __await__(self):
return self.async_init().__await__()
loop = asyncio.get_event_loop()
foo = loop.run_until_complete(Foo(settings))
Run Code Online (Sandbox Code Playgroud)
基本上这里发生的事情__init__()
像往常一样首先被调用。然后__await__()
被调用,然后等待async_init()
。
Art*_*nov 11
__ainit__
具有“异步构造函数”的AsyncObj 类:
class AsyncObj:
def __init__(self, *args, **kwargs):
"""
Standard constructor used for arguments pass
Do not override. Use __ainit__ instead
"""
self.__storedargs = args, kwargs
self.async_initialized = False
async def __ainit__(self, *args, **kwargs):
""" Async constructor, you should implement this """
async def __initobj(self):
""" Crutch used for __await__ after spawning """
assert not self.async_initialized
self.async_initialized = True
await self.__ainit__(*self.__storedargs[0], **self.__storedargs[1]) # pass the parameters to __ainit__ that passed to __init__
return self
def __await__(self):
return self.__initobj().__await__()
def __init_subclass__(cls, **kwargs):
assert asyncio.iscoroutinefunction(cls.__ainit__) # __ainit__ must be async
@property
def async_state(self):
if not self.async_initialized:
return "[initialization pending]"
return "[initialization done and successful]"
Run Code Online (Sandbox Code Playgroud)
这是“异步类”的示例:
class MyAsyncObject(AsyncObj):
async def __ainit__(self, param1, param2=0):
print("hello!", param1, param2)
# go something async, e.g. go to db
Run Code Online (Sandbox Code Playgroud)
用法:
async def example():
my_obj = await MyAsyncObject("test", 123)
Run Code Online (Sandbox Code Playgroud)
[几乎] @ojii 的规范答案
@dataclass
class Foo:
settings: Settings
pool: Pool
@classmethod
async def create(cls, settings: Settings, dsn):
return cls(settings, await create_pool(dsn))
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python3.7或更高版本,则可以使用asyncio.run:
import asyncio
# some code
class Foo(object):
async def __init(self):
self.pool = await create_pool(dsn)
def __init__(self, settings):
self.settings = settings
asyncio.run(self.__init)
foo = Foo(settings)
Run Code Online (Sandbox Code Playgroud)
请注意,如果要Foo
在已经运行的异步函数中实例化,则此方法将无效。请参阅此博客文章,以获取有关如何处理这种情况的讨论,以及有关Python中异步编程的精彩讨论。