在创建使用 asyncio 的类时,我发现自己处于属性 getter 需要进行 io 操作的情况。因此该函数应该是一个协程。然而,等待房产的感觉却很不寻常。
这是我的意思的一个最小的例子。该代码有效并且可以运行。
import asyncio
class Person:
"""A class that represents a person"""
def __init__(self, forename, surname):
self.forename = forename
self.surname = surname
@property
async def fullname(self):
"""Perform an io operation and return something.
This could be looking something up in a database for example.
"""
await asyncio.sleep(0.1)
return f"{self.forename} {self.surname}"
async def main():
john = Person("John", "Smith")
# Let's print out the forename here, using the standard property format
print(john.forename)
# When printing the full name we must instroduce an await, which feels awkward.
print(await john.fullname)
# Start the loop and run the main function
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
这是这样做的正确方法吗?
简短的回答:不要这样做。
更长的答案:作为pep8中提到 http://legacy.python.org/dev/peps/pep-0008/#designing-for-inheritance:
避免使用属性进行计算量大的操作;属性表示法使调用者相信访问(相对)便宜。
所以任何需要 IO 的东西显然都不是属性的候选者。 FWIW,我们不仅期望属性访问是廉价的,我们还期望它们是安全的(您期望属性访问可能引发 IOError、数据库错误、套接字错误或类似的错误吗?)
FWIW,你提到“等待财产感觉不寻常 https://en.wikipedia.org/wiki/Principle_of_least_astonishment“这应该已经回答了你的问题。实际上,就我而言,“异步属性”的想法让我觉得完全疯狂——属性(在语义上)与对象的状态有关,而我就是不能理解“异步状态”的概念。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)