如何告诉 PyCharm 异步装置返回某些内容

san*_*ash 6 python pytest pycharm async-await

例子:

import pytest


@pytest.fixture
async def phrase():
    return 'hello world'


@pytest.fixture
async def replaced(phrase):
    return phrase.replace('hello', 'goodbye')
Run Code Online (Sandbox Code Playgroud)

方法.replace是黄色的,并且警告说:

Unresolved attribute reference 'replace' for class 'Coroutine'
Run Code Online (Sandbox Code Playgroud)

然而,这些装置正在发挥作用。如果我asyncdef phrase():Pycharm 中删除处理.replace正确,表明它是 class 的方法str。有没有办法告诉 PyCharmphrase在使用时replacedwill 是 的实例str,而不是 a Coroutine?最好不要为每个将使用phrase.

hoe*_*ing 3

这不是您的代码,而是 Pycharm 问题 - 它无法正确解析本机协程装置的返回类型。Pycharm 将解决旧的基于生成器的协程装置

@pytest.fixture
async def phrase():
    yield 'hello world'
Run Code Online (Sandbox Code Playgroud)

作为 aGenerator[str, Any, None]并将参数映射到夹具的返回类型。然而,原生协程装置

@pytest.fixture
async def phrase():
    return 'hello world'
Run Code Online (Sandbox Code Playgroud)

是 a 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')
Run Code Online (Sandbox Code Playgroud)

切换到基于生成器的协程装置

这意味着yielding 而不是return我在评论中建议的 ing ;但是,是否应该更改明显正确的代码来解决 Pycharm 的问题取决于您。