【问题标题】:How to tell PyCharm that async fixture returns something如何告诉 PyCharm 异步夹具返回了一些东西
【发布时间】:2019-04-18 03:40:53
【问题描述】:

例子:

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'

但是,这些装置正在工作。如果我从def phrase(): 中删除async,Pycharm 正在正确处理.replace,表明它是str 类的方法。有没有办法告诉 PyCharm phrasereplaced 中使用时将是str 的一个实例,而不是Coroutine?最好不要为每个使用 phrase 的夹具重复代码。

【问题讨论】:

  • 只是一个疯狂的猜测:使用: str 进行类型提示有效吗?​​
  • 很遗憾,没有。
  • yield 'hello world' 而不是returning。
  • @hoefling 有效!考虑写一个答案?也许你知道为什么yield 有效,而return 无效?

标签: python async-await pycharm pytest


【解决方案1】:

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

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

作为Generator[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 而不是我在 cmets 中建议的returning;但是,您是否应该更改明显正确的代码来解决 Pycharm 的问题,这取决于您。

【讨论】:

  • 显式类型提示(-> str: str)并不能帮助 PyCharm 理解 phrasestr。 :(
  • 你使用的是什么 Pycharm 版本?设置显式类型提示适用于 Pycharm CE 2019.1,但不确定旧版本。
  • 专业2018.3
  • 我明天在同事的机器上测试2018.3 Pro的问题;但是,基本类型提示应该是测试 arg (replaced(phrase: str))。夹具返回类型确实可以忽略不计;为了完整起见,我插入了它们。
猜你喜欢
  • 2010-10-01
  • 1970-01-01
  • 2013-08-26
  • 2019-05-17
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 2020-08-12
  • 2018-08-09
相关资源
最近更新 更多