gpt4 book ai didi

python - 使用 asyncio 时应该如何创建属性?

转载 作者:太空宇宙 更新时间:2023-11-03 13:26:19 25 4
gpt4 key购买 nike

在创建使用 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()

这是正确的做法吗?

最佳答案

简短回答:不要这样做。

更长的答案:如mentionned in pep8 :

Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.

所以任何需要 IO 的东西显然都不是属性的候选对象。 FWIW 我们不仅希望属性访问便宜,我们还希望它们是安全的(您是否希望属性访问可能引发 IOError、数据库错误、套接字错误或任何类似错误?)

FWIW,您提到“等待属性 feels unusual”应该已经回答了您的问题。实际上,就我而言,仅仅是“异步属性”的想法就让我觉得完全疯了——属性(在语义上)与对象的状态有关,我只是无法理解“异步”的概念状态”。

关于python - 使用 asyncio 时应该如何创建属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54984337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com