如何告诉PyCharm异步夹具返回一些东西

问题描述 投票:4回答:1

例:

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的每个灯具没有代码重复。

python async-await pycharm pytest
1个回答
1
投票

这不是你的代码,它是一个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测试)。因此,您有两种可能性:

Set explicit type hints

既然你知道协程应该返回什么,设置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')

Switch to generator-based coroutine fixtures

正如我在评论中所建议的那样,这意味着yielding而不是returning;但是,你是否应该更改明显正确的代码只是为了解决Pycharm的问题。

© www.soinside.com 2019 - 2024. All rights reserved.