How can I avoid `pytest_generate_tests` being called multiple times when parent and child test classes share the same parameters?

I’m using pytest_generate_tests to dynamically parameterize tests in a parent class inherited by multiple child classes.

Since some test data is identical across children, the hook gets called multiple times unnecessarily.

How can I optimize it to avoid repeated calls?

@kusha.kpr I have run into this issue in the past as well.

pytest_generate_tests gets invoked for every test function, including those inherited by child classes.

One way to avoid redundant calls is to guard the hook using a set of already parameterized classes or functions:

_param_done = set()

def pytest_generate_tests(metafunc):
    cls = getattr(metafunc.cls, "__name__", None)
    if cls in _param_done:
        return
    if "param" in metafunc.fixturenames:
        metafunc.parametrize("param", [1, 2, 3])
    _param_done.add(cls)

This ensures each class only gets parameterized once, even if multiple children inherit the parent.

Also, a tip: if your parent class has common parameters and child classes only extend functionality, you can parameterize at the fixture level instead of using pytest_generate_tests.

For example:

import pytest

@pytest.fixture(params=[1, 2, 3])
def param(request):
    return request.param

Then every test that uses param automatically gets the values without repeatedly calling pytest_generate_tests.

This reduces complexity and avoids global state.

I ran into the same problem.

Since pytest calls pytest_generate_tests for every test method, repeated parameters can be avoided by checking the test function name or class name and skipping if already processed.

This pattern works well when you have a hierarchy of parent and child test classes.