{"record":{"id":"882bb59087b22562","repo":"pandas-dev/pandas","slug":"only-np-ndarray-extensionarray-and-index-objects","errorCode":null,"errorMessage":"Only np.ndarray, ExtensionArray, and Index objects are allowed to be passed to safe_sort as values","messagePattern":"Only np\\.ndarray, ExtensionArray, and Index objects are allowed to be passed to safe_sort as values","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/algorithms.py","lineNumber":1669,"sourceCode":"\n    Returns\n    -------\n    ordered : AnyArrayLike\n        Sorted ``values``\n    new_codes : ndarray\n        Reordered ``codes``; returned when ``codes`` is not None.\n\n    Raises\n    ------\n    TypeError\n        * If ``values`` is not list-like or if ``codes`` is neither None\n        nor list-like\n        * If ``values`` cannot be sorted\n    ValueError\n        * If ``codes`` is not None and ``values`` contain duplicates.\n    \"\"\"\n    if not isinstance(values, (np.ndarray, ABCExtensionArray, ABCIndex)):\n        raise TypeError(\n            \"Only np.ndarray, ExtensionArray, and Index objects are allowed to \"\n            \"be passed to safe_sort as values\"\n        )\n\n    sorter = None\n    ordered: AnyArrayLike\n\n    # For integer values spanning a modest range, the codes remapping below\n    #  can rank each value within that range (a counting sort) instead of\n    #  argsorting.\n    use_counting = False\n    vmin = rng_size = 0\n    if (\n        codes is not None\n        and isinstance(values, np.ndarray)\n        and values.dtype.kind in \"iu\"\n        and len(values) >= _MIN_COUNTING_SORT_LEN\n    ):","sourceCodeStart":1651,"sourceCodeEnd":1687,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/algorithms.py#L1651-L1687","documentation":"safe_sort() is an internal utility that sorts values (and optionally remaps codes). Unlike many pandas functions, it has a strict type requirement for the values argument: only numpy.ndarray, ExtensionArray, and Index are accepted. Python lists, tuples, and pandas Series are explicitly rejected. This is because safe_sort operates at a low level where it needs direct access to the underlying array buffer.","triggerScenarios":"Calling pandas.core.algorithms.safe_sort directly with a Python list as the values argument. Passing a pandas Series (which is not in the accepted type tuple) to safe_sort. Using a tuple or other sequence type that has not been converted to an ndarray or Index.","commonSituations":"Internal or library code that calls safe_sort directly. Wrapping pandas internals in a custom utility and passing unconverted list data. Misunderstanding the type requirements of internal vs. public pandas APIs.","solutions":["Convert the values to np.asarray() before passing: safe_sort(np.asarray(my_list)).","Use pd.Index() wrapping: safe_sort(pd.Index(my_list)).","If you have a Series, pass series._values or series.index as appropriate."],"exampleFix":"# before\nfrom pandas.core.algorithms import safe_sort\nsafe_sort([3, 1, 2], codes=[0, 1, 2])\n\n# after\nsafe_sort(np.array([3, 1, 2]), codes=np.array([0, 1, 2]))","handlingStrategy":"validation","validationCode":"def safe_safe_sort(values, codes=None, **kwargs):\n    if not isinstance(values, (np.ndarray, pd.Index, pd.api.extensions.ExtensionArray)):\n        values = np.asarray(values)\n    return pd.core.algorithms.safe_sort(values, codes=codes, **kwargs)","typeGuard":"def is_safe_sort_values(values) -> bool:\n    return isinstance(values, (np.ndarray, pd.Index, pd.api.extensions.ExtensionArray))","tryCatchPattern":"try:\n    result = safe_sort(values, codes)\nexcept TypeError as e:\n    if \"safe_sort as values\" in str(e):\n        result = safe_sort(np.asarray(values), codes)\n    else:\n        raise","preventionTips":["Convert all lists and tuples to np.asarray() before calling safe_sort.","Avoid calling safe_sort directly — it is an internal API; use public sorting functions when possible.","If you must use safe_sort, always validate the values type first."],"tags":["pandas","safe-sort","internal-api","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"}