Skip to content

Dynamic scope callable for pytest.fixture() cannot be correctly typed #14137

@mtnpke

Description

@mtnpke

When using the pytest.fixture decorator with a callable as the scope argument for dynamic scoping, it is not easily possible to type the callable correctly so that type checkers will, not complain.

Example:

def determine_my_client_scope(_fixture_name: str, config: pytest.Config) -> str:
    return config.getoption("--my-client-fixture-scope", "session")


@pytest.fixture(scope=determine_my_client_scope)
def my_client() -> str:
    return "Hello world!"

gives (using basedpyright):

Argument of type "(_fixture_name: str, config: Config) -> str" cannot be assigned to parameter "scope" of type "_ScopeName | ((str, Config) -> _ScopeName)" in function "fixture"
  Type "(_fixture_name: str, config: Config) -> str" is not assignable to type "_ScopeName | ((str, Config) -> _ScopeName)"
    Type "(_fixture_name: str, config: Config) -> str" is not assignable to type "(str, Config) -> _ScopeName"
      Function return type "str" is incompatible with type "_ScopeName"
        Type "str" is not assignable to type "_ScopeName"
          "str" is not assignable to type "Literal['session']"
[...]

The issue is that the _ScopeName type is private to pytest, so we cannot use it for typing the callable. It would make sense to either make this type public, so people cannot type their functions appropriately, or just use str in the typing.

pytest version: 9.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions