{"id":"50f8fc0d14e4a927","repo":"pytest-dev/pytest","slug":"pytest-approx-only-supports-ordered-sequences-b","errorCode":null,"errorMessage":"pytest.approx() only supports ordered sequences, but got: {expected!r}","messagePattern":"pytest\\.approx\\(\\) only supports ordered sequences, but got: (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/_pytest/approx.py","lineNumber":967,"sourceCode":"    # The actual logic for making approximate comparisons can be found in\n    # ApproxScalar, which is used to compare individual numbers.  All of the\n    # other Approx classes eventually delegate to this class.  The ApproxBase\n    # class provides some convenient methods and overloads, but isn't really\n    # essential.\n\n    __tracebackhide__ = True\n\n    if isinstance(expected, Decimal):\n        return ApproxDecimal(expected, rel=rel, abs=abs, nan_ok=nan_ok)  # type: ignore[return-value]\n    elif isinstance(expected, Mapping):\n        return ApproxMapping(expected, rel=rel, abs=abs, nan_ok=nan_ok)  # type: ignore[return-value]\n    elif (np_array := _as_numpy_array(expected)) is not None:\n        return ApproxNumpy(np_array, rel=rel, abs=abs, nan_ok=nan_ok)\n    elif _is_sequence_like(expected):\n        return ApproxSequenceLike(expected, rel=rel, abs=abs, nan_ok=nan_ok)  # type: ignore[return-value]\n    elif isinstance(expected, Collection) and not isinstance(expected, str | bytes):\n        msg = f\"pytest.approx() only supports ordered sequences, but got: {expected!r}\"\n        raise TypeError(msg)\n    elif isinstance(expected, (datetime, timedelta)):\n        return ApproxTimedelta(expected, rel=rel, abs=abs, nan_ok=nan_ok)  # type: ignore[return-value]\n    else:\n        return ApproxScalar(expected, rel=rel, abs=abs, nan_ok=nan_ok)\n\n\ndef _is_sequence_like(expected: object) -> TypeGuard[Sequence[Any]]:\n    return (\n        hasattr(expected, \"__getitem__\")\n        and isinstance(expected, Sized)\n        and not isinstance(expected, str | bytes)\n    )\n\n\ndef _as_numpy_array(obj: object) -> ndarray | None:\n    \"\"\"\n    Return an ndarray if the given object is implicitly convertible to ndarray,\n    and numpy is already imported, otherwise None.","sourceCodeStart":949,"sourceCodeEnd":985,"githubUrl":"https://github.com/pytest-dev/pytest/blob/98b357f69e380da908740a212288d73b2ee06687/src/_pytest/approx.py#L949-L985","documentation":"The approx() dispatcher accepts Decimal, Mapping, numpy array, sequence-like objects, datetime/timedelta, and scalars — but a Collection that is NOT ordered (no __getitem__) is unsupported. The classic case is a set. pytest refuses because element order is required to pair up actual vs expected values.","triggerScenarios":"Call pytest.approx({1, 2, 3}) (a set) or any Collection lacking __getitem__. The dispatcher hits the `isinstance(expected, Collection) and not str/bytes` branch after sequence-like and Mapping checks fail.","commonSituations":"Passing a set to approx() expecting unordered membership comparison; passing a frozenset; passing a custom Collection that does not implement sequence protocol.","solutions":["Convert to an ordered structure: approx([1, 2, 3]) (list) or approx((1,2,3)) (tuple).","If you want set-like membership, write the assertion explicitly: assert set(actual) == set(expected).","For custom containers, implement __getitem__ and Sized or pass an iterable wrapped in list()."],"exampleFix":"// before\nassert actual == approx({1, 2, 3})\n// after\nassert actual == approx([1, 2, 3])","handlingStrategy":"type-guard","validationCode":"from collections.abc import Collection, Sequence\n\ndef approx_seq(expected):\n    if isinstance(expected, Collection) and not isinstance(expected, str | bytes | Sequence):\n        # unordered collection (e.g. set) — sort or convert before approx\n        expected = sorted(expected)\n    return pytest.approx(expected)","typeGuard":"from collections.abc import Sequence\n\ndef is_ordered_sequence(v) -> bool:\n    return isinstance(v, Sequence) and not isinstance(v, (str, bytes))","tryCatchPattern":null,"preventionTips":["Always convert sets/frozensets to sorted lists before passing to approx().","If order does not matter, assert set equality directly instead of using approx().","For custom containers, implement __getitem__ and Sized so they are recognized as sequence-like."],"tags":["pytest","approx","type-mismatch","collections"],"analyzedSha":"98b357f69e380da908740a212288d73b2ee06687","analyzedAt":"2026-08-04T20:26:34.442Z","schemaVersion":2}