python type_error ai_generated true

TypeError: '<' not supported between instances of 'int' and 'str'

ID: python/pytest-parametrize-id-special-chars

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-08-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

Passing mixed types as `ids=` to `@pytest.mark.parametrize` (e.g. ids=[1, 'two']) causes pytest to sort them for display, which fails when comparing int and str.

generic

中文

向 `@pytest.mark.parametrize` 的 `ids=` 传入混合类型(如 ids=[1, 'two'])会使 pytest 在显示时排序它们,比较 int 与 str 时失败。

Workarounds

  1. 95% success
    Cast all ids to strings:
    
    @pytest.mark.parametrize('n', [1, 2, 3], ids=lambda n: f'case-{n}')
  2. 90% success
    Provide a callable for ids that returns unique strings:
    
    ids=lambda v: str(v).replace(' ', '_')

Dead Ends

Common approaches that don't work:

  1. 30% fail

    Works, but loses readability; long parameter values produce unreadable test IDs.

  2. 90% fail

    Sorting mixed types raises the same TypeError before pytest even sees it.