pandas-dev/pandas · error · TypeError
Only list-like objects or None are allowed to be passed to…
Error message
Only list-like objects or None are allowed to be passed to safe_sort as codes
What it means
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.
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.
Example fix
# before safe_sort(values, codes=3) # after safe_sort(values, codes=[3])
Defensive patterns
Strategy: validation
Validate before calling
from pandas.api.types import is_list_like
def safe_safe_sort(values, codes=None, **kwargs):
if codes is not None and not is_list_like(codes):
raise TypeError(f"codes must be list-like or None, got {type(codes).__name__}")
return pd.core.algorithms.safe_sort(values, codes=codes, **kwargs) Type guard
from pandas.api.types import is_list_like
def is_valid_codes(codes) -> bool:
return codes is None or is_list_like(codes) Try / catch
try:
result = safe_sort(values, codes)
except TypeError as e:
if "safe_sort as codes" in str(e):
result = safe_sort(values, [codes] if codes is not None else None)
else:
raise Prevention
- 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).
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Only np.ndarray, ExtensionArray, and Index objects are…
- requires a Series, Index, ExtensionArray, np.ndarray or…
- only list-like objects are allowed to be passed to isin()…
- only list-like objects are allowed to be passed to isin()…
- pd.api.extensions.take requires a numpy.ndarray…
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/8b08747ad0bab142.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/algorithms.py:1730
except (TypeError, decimal.InvalidOperation):
# Previous sorters failed or were not applicable, try `_sort_mixed`
# which would work, but which fails for special case of 1d arrays
# with tuples.
if values.size and isinstance(values[0], tuple):
# error: Argument 1 to "_sort_tuples" has incompatible type
# "Union[Index, ExtensionArray, ndarray[Any, Any]]"; expected
# "ndarray[Any, Any]"
ordered = _sort_tuples(values) # type: ignore[arg-type]
else:
ordered = _sort_mixed(values)
# codes:
if codes is None:
return ordered
if not is_list_like(codes):
raise TypeError(
"Only list-like objects or None are allowed to "
"be passed to safe_sort as codes"
)
codes = ensure_platform_int(np.asarray(codes))
# ranks[i] gives the position of values[i] in `ordered`
if use_counting:
arr = cast("np.ndarray", values)
if arr.dtype.kind == "i":
# go through int64 so differences don't overflow narrower signed
# dtypes; int64 wraparound is exact since the true differences
# are within rng_size
shifted = arr.astype(np.int64, copy=False) - vmin
else:
# unsigned: differences always fit the unsigned dtype
shifted = arr - vmin
present = np.zeros(rng_size, dtype=bool)
present[shifted] = TrueView on GitHub (pinned to 3b7651241d)