python - 如何告诉 PyCharm 异步夹具返回了一些东西
问题描述
例子:
import pytest
@pytest.fixture
async def phrase():
return 'hello world'
@pytest.fixture
async def replaced(phrase):
return phrase.replace('hello', 'goodbye')
该方法.replace
是黄色的,警告说:
Unresolved attribute reference 'replace' for class 'Coroutine'
但是,这些固定装置正在工作。如果我async
从def phrase():
Pycharm 中删除处理.replace
正确,表明它是 class 的方法str
。有没有办法告诉 PyCharmphrase
在使用时replaced
将是 的实例str
,而不是Coroutine
?最好不要对每个将使用phrase
.
解决方案
这不是您的代码,而是 Pycharm 问题 - 它无法正确解析本机协程装置的返回类型。Pycharm 将解决旧的基于生成器的协程夹具
@pytest.fixture
async def phrase():
yield 'hello world'
作为 aGenerator[str, Any, None]
并将参数映射到夹具的返回类型。然而,一个原生协程夹具
@pytest.fixture
async def phrase():
return 'hello world'
是一个Coroutine[Any, Any, str]
,目前,Pycharm 没有将测试参数映射到它的返回类型(使用 Pycharm CE 2019.1 测试)。因此,您有两种可能性:
设置显式类型提示
既然你知道协程应该返回什么,设置 return 和 arg 类型,Pycharm 就会停止猜测。这是最直接和最强大的方法:
@pytest.fixture
async def phrase() -> str:
return 'hello world'
@pytest.fixture
async def replaced(phrase: str) -> str:
return phrase.replace('hello', 'goodbye')
切换到基于生成器的协程装置
这意味着yield
ing 而不是return
我在评论中建议的 ing;但是,是否应该更改明显正确的代码只是为了解决 Pycharm 的问题,这取决于您。
推荐阅读
- pandas - 当另一个数据框列中的列表项匹配时更新数据框中的 NaN 值
- java - ServiceLoader.load 如何与 JPMS 中的类加载器一起工作?
- python - 使用 shift() 比较 Pandas Dataframe 中的行
- sql-server - 如何在数据集中查找度量
- python - 无法使用 beautifulsoup 和 requests 进行网页抓取
- python - 无法使用 mysql.connector 从 SQL 获取结果到 Python
- mysql - 如何通过拆分table1中teacher_id的值来编写查询以获取table2中的teacher_name
- r - 创建多个变量的多图分布到一个
- shell - 使用 docker -c 选项在 shell 脚本中将 if 语句作为单行运行
- python - 我想要一个可配置的 python 可调用。类与函数工厂?