{"record":{"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/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/approx.py#L949-L985","documentation":"Raised by the approx() factory when expected is a Collection (and not str/bytes) but is not ordered — i.e., it lacks __getitem__ or is not a Sequence. The dispatch first checks Decimal, Mapping, numpy array, then sequence-like objects; an unordered collection (e.g. a set) falls through to the Collection branch and is rejected because approx comparison needs positional correspondence. datetime/timedelta and scalars are handled in later branches.","triggerScenarios":"approx({1, 2, 3}) (a set); approx(frozenset(...)); approx(some_custom_collection_without_getitem).","commonSituations":"Asserting on set-valued results without converting to a sorted list; using approx on unordered collection types; custom collections that register as Collection but aren't subscriptable.","solutions":["Convert to a sorted list: approx(sorted(my_set)).","Convert to a tuple preserving intended order: approx(tuple(my_collection)).","For unordered comparison, compare as a set explicitly rather than via approx()."],"exampleFix":"// before\nassert result_set == approx({1, 2, 3})\n// after\nassert sorted(result_set) == approx(sorted([1, 2, 3]))","handlingStrategy":"type-guard","validationCode":"from collections.abc import Collection, Sequence\ndef approx_collection(expected, **kw):\n    if isinstance(expected, Collection) and not isinstance(expected, (str, bytes, Sequence)):\n        expected = sorted(expected)\n    return approx(expected, **kw)","typeGuard":"from collections.abc import Sequence\ndef is_approximable_sequence(v) -> bool:\n    return isinstance(v, Sequence) or hasattr(v, '__getitem__')","tryCatchPattern":null,"preventionTips":["Convert sets to sorted lists before approx().","Check the type is a Sequence (not just Collection) before approximating."],"tags":["approx","sequence","collection","type-mismatch"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}