API Reference

This page outlines the public functions, enumerations, and typing helpers exposed by the natsort package.

Core Sorting Functions

natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT)

The primary function of the library. Takes an iterable and returns a naturally sorted list.

Parameters:

  • seq (Iterable[T]): The input iterable to sort.
  • key (Callable[[T], NatsortInType] | None): A key function used to extract a comparison value from each element. It operates strictly element-wise and is not applied recursively.
  • reverse (bool): Return the list in reversed (descending) sorted order. Default is False.
  • alg (NSType): Bitwise configuration controlling the internal algorithm. See the ns Enum section below. Default is ns.INT.

Returns:

  • list[T]: The naturally sorted list of inputs.

natsort_keygen(key=None, alg=ns.DEFAULT)

Generates a standalone sorting key function. Designed for use as the key argument in standard Python library functions like sorted() and list.sort() to sort massive lists in-place without copying data.

Parameters:

  • key (Callable | None): A custom key used to manipulate the input value before parsing for numbers.
  • alg (NSType): Bitwise configuration. Default is ns.INT.

Returns:

  • Callable[[Any], NatsortOutType]: A factory closure function that parses input strings into a stable, comparable tuple.

Note: natsort_key is exposed as a convenience property, representing the pre-instantiated output of natsort_keygen() using all default parameters.


os_sorted(seq, key=None, reverse=False, presort=False)

Sort elements exactly mimicking your operating system's native file browser (e.g., Windows Explorer, macOS Finder, Linux File Managers).

Warning: Because OS algorithms differ, the resulting output will intentionally differ depending on the platform executing the code. On Windows, it binds to windll.Shlwapi.StrCmpLogicalW. On Unix, it binds to icu.Collator.

Parameters:

  • seq (Iterable[T]): The input to sort. Each element must evaluate to type str.
  • key (Callable): A key function to pre-process elements.
  • reverse (bool): Return in reversed order. Default False.
  • presort (bool): Equivalent to adding ns.PRESORT. Default False.

Returns:

  • list[T]: The OS-style sorted list.

Note: os_sort_keygen(key=None) and os_sort_key are also available for in-place sorting generation.


Convenience Wrappers

These functions pre-apply specific ns configurations to natsorted for common workflows.

  • humansorted(seq, key=None, reverse=False): Sort an iterable naturally while appropriately ordering non-numeric characters in a localized manner. Equivalent to natsorted(seq, alg=ns.LOCALE).
  • realsorted(seq, key=None, reverse=False): Sort an iterable naturally while properly parsing and sorting signed floats and exponential notation. Equivalent to natsorted(seq, alg=ns.REAL).

Index Management

Sometimes you don't want to sort the data itself, but rather obtain the list of indexes that representing the sorted order. This is useful for synchronizing the sorting of parallel arrays or pandas DataFrames.

  • index_natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT): Returns a list[int] representing the naturally sorted indexes.
  • index_humansorted(...): Equivalent to index_natsorted(..., alg=ns.LOCALE).
  • index_realsorted(...): Equivalent to index_natsorted(..., alg=ns.REAL).

order_by_index(seq, index, iter=False)

Re-order a given sequence strictly mapping to a previously evaluated index sequence generated by index_natsorted.

Returns:

  • A list containing the reordered elements. If iter=True, returns a memory-efficient generator iterator instead.

Type Casting & Helper Functions

  • decoder(encoding): Returns an isolated function designed to decode bytes objects to str utilizing the specifically passed encoding schema.
  • as_ascii(s): Decodes an input with the ASCII codec if it matches type bytes, otherwise bypasses and returns as-is.
  • as_utf8(s): Decodes an input with the UTF-8 codec if it matches type bytes, otherwise bypasses and returns as-is.
  • chain_functions(functions): Sequential composition utility chaining a list of single-argument functions together (useful for building complex key lambdas).
  • numeric_regex_chooser(alg): Dynamically selects and returns the underlying regex pattern string used by natsort for isolating numbers as defined by the matching alg configuration.

The ns Enum

The ns enum configuration acts as a bitmask to modify the behavior of the internal natsort parsing algorithms. Combine configurations concurrently via the bitwise OR operator (|).

Attribute / Alias Description
ns.INT / ns.I Parse sequential numbers as standard integers (Default).
ns.FLOAT / ns.F Parse sequential numbers natively as floats.
ns.UNSIGNED / ns.U Ignore trailing signs (+/-) formatting the left of numbers (Default).
ns.SIGNED / ns.S Evaluate and account for tracking signs (+/-) to the left of numbers.
ns.REAL / ns.R Consolidated shortcut mapping to ns.FLOAT \\| ns.SIGNED.
ns.NOEXP / ns.N Suppress evaluation of numerical exponents (e.g., interpret 1e4 as text).
ns.NUMAFTER / ns.NA Deprioritize numerical entries sorting them strictly after non-numeric text.
ns.PATH / ns.P Parse string inputs natively as hierarchical filesystem components. Splits extensions so folder/ isn't sorted after folder (1)/.
ns.COMPATIBILITYNORMALIZE / ns.CN Execute Unicode Normalization standard "NFKD" instead of the default "NFD".
ns.LOCALE / ns.L Activate full locale-aware sorting (Alphabetical + localized numeric decimals).
ns.LOCALEALPHA / ns.LA Activate targeted locale-aware sorting, restricting mapping to alphabetical tokens.
ns.LOCALENUM / ns.LN Activate targeted locale-aware sorting, restricting mapping to localized decimals/thousands separators.
ns.IGNORECASE / ns.IC Disable casing evaluations ignoring text case entirely.
ns.LOWERCASEFIRST / ns.LF Prioritize lowercase character tokens over matching uppercase tokens.
ns.GROUPLETTERS / ns.G Evaluate and group lowercase and uppercase characters natively together (e.g., A, a, B, b).
ns.CAPITALFIRST / ns.C / ns.UG Explicitly position capitalized prefixes before uncapitalized tokens (Applied only in LOCALE mode).
ns.NANLAST / ns.NL Redefine parsing of NaN and None. Default treats them as -Infinity (front). This shifts them to +Infinity (end).
ns.PRESORT / ns.PS Pre-sort strings natively before natural sorting. Resolves order ambiguity when strings visually differ but evaluate to the exact same numbers (e.g., "a01" vs "a1").