How can I properly type hint the `pytestconfig` fixture in pytest?

How can I properly type hint the pytestconfig fixture in pytest?

Currently, to annotate the pytestconfig fixture, one has to import _pytest.config.Config.

However, the leading underscore suggests it’s not intended for external use.

Is there a way to properly expose this class for type hints, or what is the recommended approach to type-hint the pytestconfig fixture in a safe and maintainable way?

It’s true that _pytest.config.Config has a leading underscore, but for type hinting, it’s generally safe to use it.

For example:

import pytest
from _pytest.config import Config

def test_example(pytestconfig: Config):
    assert pytestconfig.getoption("verbose") >= 0

Since type hints don’t affect runtime, using the internal class just for annotation purposes won’t break anything. I’ve used this approach in several projects without issues.

If you want to avoid relying on a protected member entirely, you can type hint with Any from the typing module:

from typing import Any
import pytest

def test_example(pytestconfig: Any):
    assert pytestconfig.getoption("verbose") >= 0

It’s less precise but avoids accessing internal modules. I find this useful when maintaining compatibility across different pytest versions.

For more maintainable code, you can define a protocol that includes only the attributes you use.

For example:

from typing import Protocol

class PytestConfigProtocol(Protocol):
    def getoption(self, name: str):
        ...

def test_example(pytestconfig: PytestConfigProtocol):
    assert pytestconfig.getoption("verbose") >= 0

This approach is safe, doesn’t depend on internal _pytest modules, and keeps your type hints meaningful. It works really well if you only need a subset of Config’s functionality.