首页 > 解决方案 > 如何告诉 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'

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

标签: pythonasync-awaitpycharmpytest

解决方案


这不是您的代码,而是 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')

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

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


推荐阅读