[Python] How does `pytest.mark.parametrize` infer a Literal type for a function argument?

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using pytest.mark.parametrize in my test function, and I noticed something interesting when hovering over the input parameter in VSCode. The inferred type is:

    input: Literal['bar', 'baz', 'BAR'] | None


    Here is my test code:

    @pytest.mark.parametrize(
    "input,status_code,expected",
    [
    ("bar", status.HTTP_200_OK, "bar"),
    ("baz", status.HTTP_200_OK, "baz"),
    (None, status.HTTP_422_UNPROCESSABLE_ENTITY, None),
    ("BAR", status.HTTP_200_OK, "BAR"),
    ],
    )
    def test_path(app, input, status_code, expected):
    @app.get("/items/{item_id}")
    def read_item(item_id: Annotated[str, Path()]):
    assert item_id == expected

    res = read_item({"pathParameters": {"item_id": input}}, {})
    assert res["statusCode"] == status_code


    It seems like pytest.mark.parametrize is influencing the inferred type of input, making it a Literal type based on the provided test cases.

    My questions:

    1. How does pytest.mark.parametrize affect the type inference of function parameters?
    2. How to add type hints for function arguments by only using decorators in Python

    I couldn't find documentation explicitly mentioning this behavior, so I'd appreciate any insights or references.

    [​IMG]

    Continue reading...

Compartilhe esta Página