Skip to content

Type annotation for fixtures #5981

Description

@sodul

As reported by others, the fact that fixture can exist magically is confusing for many users unfamiliar with pytest and it can be gruesome to track in larger projects with many fixtures.

Since type annotation is working well in python 3 I was thinking that one explicit way would be to have a new Fixture type to help annotate the fixture arguments.

from typing import Union
import pytest

Fixture = Union

@pytest.fixture
def bob() -> str:
    return '42'

@pytest.fixture
def alice() -> int:
    return 42

def test_foo(bob: Fixture[str], alice: Fixture[int]):
    assert bob != alice

In this example I 'abuse' Union so that existing tools are taking the hinting without any issue. For the person coming in and reading the code, especially in larger projects, the fact that the arguments are fixtures becomes very explicit and in the spirit of the Zen of Python:

Explicit is better than implicit.

Unfortunately mypy and other type checking tools don't seem to 'alias' Union since it is a special case.

This on the other hand works but I would prefer the annotation of the first example:

from typing import Union
import pytest

@pytest.fixture
def bob() -> str:
    return '42'

@pytest.fixture
def alice() -> int:
    return 42

FixtureStr = Union[str]
FixtureInt = Union[int]

def test_bar(bob: FixtureStr, alice: FixtureInt):
    assert bob != alice

IDEs such as PyCharm then now able to hint on bob being a string and as a user I can tell that it is a fixture argument.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: fixturesanything involving fixtures directly or indirectlytype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions