{"record":{"id":"8b08747ad0bab142","repo":"pandas-dev/pandas","slug":"only-list-like-objects-or-none-are-allowed-to-be-p","errorCode":null,"errorMessage":"Only list-like objects or None are allowed to be passed to safe_sort as codes","messagePattern":"Only list-like objects or None are allowed to be passed to safe_sort as codes","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/algorithms.py","lineNumber":1730,"sourceCode":"        except (TypeError, decimal.InvalidOperation):\n            # Previous sorters failed or were not applicable, try `_sort_mixed`\n            # which would work, but which fails for special case of 1d arrays\n            # with tuples.\n            if values.size and isinstance(values[0], tuple):\n                # error: Argument 1 to \"_sort_tuples\" has incompatible type\n                # \"Union[Index, ExtensionArray, ndarray[Any, Any]]\"; expected\n                # \"ndarray[Any, Any]\"\n                ordered = _sort_tuples(values)  # type: ignore[arg-type]\n            else:\n                ordered = _sort_mixed(values)\n\n    # codes:\n\n    if codes is None:\n        return ordered\n\n    if not is_list_like(codes):\n        raise TypeError(\n            \"Only list-like objects or None are allowed to \"\n            \"be passed to safe_sort as codes\"\n        )\n    codes = ensure_platform_int(np.asarray(codes))\n\n    # ranks[i] gives the position of values[i] in `ordered`\n    if use_counting:\n        arr = cast(\"np.ndarray\", values)\n        if arr.dtype.kind == \"i\":\n            # go through int64 so differences don't overflow narrower signed\n            #  dtypes; int64 wraparound is exact since the true differences\n            #  are within rng_size\n            shifted = arr.astype(np.int64, copy=False) - vmin\n        else:\n            # unsigned: differences always fit the unsigned dtype\n            shifted = arr - vmin\n        present = np.zeros(rng_size, dtype=bool)\n        present[shifted] = True","sourceCodeStart":1712,"sourceCodeEnd":1748,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/algorithms.py#L1712-L1748","documentation":"safe_sort() accepts an optional codes argument — an array of integer indices into the values array that should be remapped after sorting. This argument must be either None (to skip code remapping) or list-like (array, list, tuple of ints). Passing a scalar, a dict, or any non-iterable triggers this TypeError. The codes are used to reindex categorical or factorized data after sorting the unique values.","triggerScenarios":"Calling safe_sort(values, codes=5) with a scalar instead of an array. Passing None where a value was intended, or passing a non-integer iterable like a dict. Accidentally passing the values argument in the codes position.","commonSituations":"Calling safe_sort with positional arguments in the wrong order. Passing a single integer code instead of an array of codes. Using safe_sort in a loop where the codes variable is sometimes None and sometimes a scalar.","solutions":["Wrap scalar codes in a list: safe_sort(values, codes=[code]).","Pass None explicitly if you do not need code remapping.","Verify the argument order: safe_sort(values, codes) — values first, codes second."],"exampleFix":"# before\nsafe_sort(values, codes=3)\n\n# after\nsafe_sort(values, codes=[3])","handlingStrategy":"validation","validationCode":"from pandas.api.types import is_list_like\n\ndef safe_safe_sort(values, codes=None, **kwargs):\n    if codes is not None and not is_list_like(codes):\n        raise TypeError(f\"codes must be list-like or None, got {type(codes).__name__}\")\n    return pd.core.algorithms.safe_sort(values, codes=codes, **kwargs)","typeGuard":"from pandas.api.types import is_list_like\n\ndef is_valid_codes(codes) -> bool:\n    return codes is None or is_list_like(codes)","tryCatchPattern":"try:\n    result = safe_sort(values, codes)\nexcept TypeError as e:\n    if \"safe_sort as codes\" in str(e):\n        result = safe_sort(values, [codes] if codes is not None else None)\n    else:\n        raise","preventionTips":["Always pass codes as a numpy array or None to safe_sort.","Wrap individual code values in a list before passing.","Double-check the argument order: safe_sort(values, codes)."],"tags":["pandas","safe-sort","internal-api","codes","type-validation","typeerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}