[Python] Best practice to organize pytest fixtures to prevent linter redefined-outer-name...

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a conftest.py file in my pytest tests where I define multiple fixtures. Some fixtures depend on others and share the same or very similar names, which triggers the pylint warning:

    W0621: Redefining name 'page_views_and_downloads_provider_class_mock' from outer scope (redefined-outer-name)


    Here is a simplified example of my code:

    @pytest.fixture
    def page_views_and_downloads_provider_class_mock(request) -> Iterator[MagicMock]:
    cli_module = getattr(request, "param", None)
    with patch.object(cli_module, 'PageViewsAndDownloadsProvider') as mock:
    yield mock

    @pytest.fixture
    def page_views_and_downloads_provider_mock(
    page_views_and_downloads_provider_class_mock: MagicMock
    ) -> MagicMock:
    return page_views_and_downloads_provider_class_mock.return_value


    If I try to rename the argument in the second fixture to avoid the warning, like below, I get an error during testing that says the test function uses no fixture named 'page_views_and_downloads_provider_class_mock'.

    @pytest.fixture
    def page_views_and_downloads_provider_mock(
    provider_class_mock: MagicMock
    ) -> MagicMock:
    return provider_class_mock.return_value


    I also tried duplicating the fixture code inside each test file like below and that suppresses the warning but causes a lot of code duplication between files, which I want to avoid.

    @pytest.fixture(name='page_views_and_downloads_provider_class_mock', autouse=True)
    def _page_views_and_downloads_provider_class_mock() -> Iterator[MagicMock]:
    with patch.object(cli_module, 'PageViewsAndDownloadsProvider') as mock:
    yield mock


    @pytest.fixture(name='page_views_and_downloads_provider_mock')
    def _page_views_and_downloads_provider_mock(
    page_views_and_downloads_provider_class_mock: MagicMock
    ) -> MagicMock:
    return page_views_and_downloads_provider_class_mock.return_value


    I also tried disabling the pylint warning globally with # pylint: disable=redefined-outer-name but that didn't disable the warning.

    What is the best practice to structure pytest fixtures to avoid this pylint warning without breaking pytest or duplicating code?

    Continue reading...

Compartilhe esta Página