6

Example:

import pytest


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


@pytest.fixture
async def replaced(phrase):
    return phrase.replace('hello', 'goodbye')

The method .replace is yellow-colored and the warning says:

Unresolved attribute reference 'replace' for class 'Coroutine'

However, these fixtures are working. If I remove async from def phrase(): Pycharm is handling .replace correctly, showing that it is method of class str. Is there any way to tell PyCharm that phrase when used in replaced will be an instance of str, not a Coroutine? Preferably, without code repetition for every fixture that will use phrase.

sanyassh
  • 8,100
  • 13
  • 36
  • 70

1 Answers1

3

It's not your code, it's a Pycharm issue - it doesn't resolve return types of native coroutine fixtures correctly. Pycharm will resolve the old generator-based coroutine fixture

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

as a Generator[str, Any, None] and map the argument to the fixture's return type. However, a native coroutine fixture

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

is a Coroutine[Any, Any, str] and currently, Pycharm doesn't map the test args to its return type (tested with Pycharm CE 2019.1). You thus have two possibilities:

Set explicit type hints

Since you know what the coroutines should return, set the return and arg types and Pycharm will stop guessing. This is the most straightforward and robust approach:

@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

This would mean yielding instead of returning as I suggested in the comments; however, it's up to you whether you should change the obviously correct code just to work around Pycharm's issue.

hoefling
  • 59,418
  • 12
  • 147
  • 194
  • Explicit type hints (both `-> str` and `: str`) doesn't help PyCharm to understand that `phrase` is a `str`. :( – sanyassh Apr 17 '19 at 19:45
  • What Pycharm version are you using? Setting explicit type hints works with Pycharm CE 2019.1, not sure about older versions though. – hoefling Apr 17 '19 at 19:47
  • Professional 2018.3 – sanyassh Apr 17 '19 at 19:48
  • I will test the issue with 2018.3 Pro tomorrow on a colleague's machine; however, the essential type hint should be the test arg (`replaced(phrase: str)`). The fixture return types are indeed negligible; I inserted them for completeness sake. – hoefling Apr 17 '19 at 19:52
  • 1
    don't believe this is still open issue – xiº Feb 01 '23 at 13:43
  • https://github.com/theY4Kman/pycharm-pytest-imp this plugin fixes that issue – xiº Feb 02 '23 at 10:33