'How can request.param be annotated in indirect parametrization?

In the Indirect parametrization example I want to type hint request.param indicating a specific type, a str for example.

The problem is since the argument to fixt must be the request fixture there seems to be no way to indicate what type the parameters passed through the "optional param attribute" should be (quoting the documentation).

What are the alternatives? Perhaps documenting the type hint in the fixt docstring, or in the test_indirect docstring?

@pytest.fixture
def fixt(request):
    return request.param * 3

@pytest.mark.parametrize("fixt", ["a", "b"], indirect=True)
def test_indirect(fixt):
    assert len(fixt) == 3


Solution 1:[1]

Following up on hoefling's answer regarding generics, you can wrangle the generic into the TYPE_CHECKING code:

from typing import TYPE_CHECKING, Generic, TypeVar

if TYPE_CHECKING:
    from pytest import FixtureRequest as _FixtureRequest
    T = TypeVar("T")
    class FixtureRequest(_FixtureRequest, Generic[T]):
        param: T
else:
    from pytest import FixtureRequest

Then code like this will work, though you may need to quote the type hint since pytest's FixtureRequest is not generic at runtime:

@pytest.fixture
def fixt(request: "FixtureRequest[str]") -> str:
    return request.param * 3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brendan Batliner