例:
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
,表明它是类str
的方法。有没有办法告诉PyCharm phrase
用于replaced
将是str
的一个实例,而不是Coroutine
?优选地,对于将使用phrase
的每个灯具没有代码重复。
这不是你的代码,它是一个Pycharm问题 - 它无法正确解析原生协程装置的返回类型。 Pycharm将解决旧的基于发生器的协同装置
@pytest.fixture
async def phrase():
yield 'hello world'
作为Generator[str, Any, None]
并将参数映射到fixture的返回类型。但是,一个原生的coroutine夹具
@pytest.fixture
async def phrase():
return 'hello world'
是一个Coroutine[Any, Any, str]
,目前,Pycharm没有将测试args映射到其返回类型(使用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的问题。