natsort

repository·main·Indexed 21 days ago

https://github.com/sethmmorton/natsort

A Python library providing flexible natural sorting algorithms that handle numbers within strings according to human intuition (e.g., '2' before '10'). It includes specialized tools for versioning, file paths, and locale-aware sorting, as well as a command-line interface for sorting entries with support for numeric range filtering and OS-style sorting.

Tokens
7K
Snippets
32
Records
44
Agent score
76%

What's inside natsort

  1. Customize natsort using the ns enum and bitwise OR

    main

    You can combine multiple sorting algorithms and modifiers using the bitwise OR operator (|) with the ns enum. The ns enum provides both long names (e.g., ns.LOCALE) and short forms (e.g., ns.L).

    Available modifiers include:

    • ns.REAL / ns.R (Signed floats)
    • ns.LOCALE / ns.L (Locale-aware)
    • ns.IGNORECASE / ns.IC (Case-insensitive)
    from natsort import natsorted, ns
    
    a = ['Apple', 'apple15', 'Banana', 'apple14,689', 'banana']
    
    # Combine multiple modifiers
    natsorted(a, alg=ns.REAL | ns.LOCALE | ns.IGNORECASE)
    
    # Using short forms
    natsorted(a, alg=ns.R | ns.L | ns.IC)
  2. How natsort works and how to use natsort_keygen()

    main

    The natsort library provides a key function that can be passed to standard Python sorting methods like list.sort() or sorted(). This key is generated using natsort_keygen().

    natsorted() is essentially a wrapper that uses this key generator. The key returned by natsort_keygen() always returns a tuple by attempting to split strings into numbers (converted to int or float) and non-numbers, or recursively applying the key to sequences.

    from natsort import natsort_keygen
    
    natsort_key = natsort_keygen()
    sorted_list = sorted(['1', '10', '2'], key=natsort_key)
    # Result: ['1', '2', '10']
  3. Debug natsorted() using natsort_keygen()

    main

    If you are experiencing unexpected sorting results, the best way to debug is to generate the sort key manually using natsort_keygen() with the same options used in your natsorted() call. This allows you to inspect exactly how the input data is being transformed into the comparison tuple.

    from natsort import natsort_keygen
    
    # Use the same options you passed to natsorted()
    key_func = natsort_keygen(alg='...') 
    
    # Inspect the key for a problematic item
    print(key_func('problematic_item'))
  4. Install natsort with optional dependencies

    main

    You can install optional dependencies using the extras notation at installation time:

    • Use fast to install fastnumbers (version >=2.0.0), which improves efficiency for string-to-number conversions.
    • Use icu to install PyICU, which is recommended for locale-dependent sorting.

    To install both:

    pip install natsort[fast,icu]

    To install only fastnumbers:

    pip install natsort[fast]
  5. Configure the natsort algorithm using the `ns` enum

    main

    The ns enum (an IntEnum) is used to control the natsort algorithm via the alg parameter in natsort functions. You can combine multiple options simultaneously using the bitwise OR operator (|).

    For example, to use integer parsing, path awareness, and locale awareness, you would use ns.INT | ns.PATH | ns.LOCALE.

    import natsort as ns
    a = ["num5.10", "num-3", "num5.3", "num2"]
    # Using the REAL shortcut (FLOAT | SIGNED)
    sorted_list = ns.natsorted(a, alg=ns.REAL)
  6. Access sorting types via the ns namespace

    main

    The ns object (an instance of NSType) provides access to various sorting type constants. For convenience, these members are also exported directly into the natsort package namespace.

    from natsort import ns, NSType
    
    # You can use the ns namespace
    # or the direct exports provided by the package
  7. Use the natsort CLI to sort entries

    main

    The natsort command-line interface performs natural sorting on a list of entries provided via command-line arguments or stdin. It supports filtering by numeric ranges, excluding specific numbers, and configuring how numbers (integers, floats, signed, etc.) are interpreted.

    Input Sources

    • Command-line arguments: Pass entries directly as arguments.
    • Standard Input (stdin): If no arguments are provided, the tool reads from stdin. By default, it splits entries by newlines. Use the -z or --zero-terminated flag to split on null characters (\0) instead.

    Common Tasks

    • Sort file paths: Use -p or --paths to ensure OS-style paths (like Folder/ and Folder (1)/) are sorted in the expected order.
    • Filter by numeric range: Use -f or --filter to keep only entries containing a number within a specific LOW to HIGH range. You can provide multiple ranges.
    • Exclude by numeric range: Use -F or --reverse-filter to exclude entries containing numbers within a specific range.
    • Exclude specific numbers: Use -e or --exclude to remove entries that contain a specific number.
    • Change sort order: Use -r or --reverse to return results in descending order.
    • Configure number types: Use -t or --number-type to specify if the tool should look for int, float, or real (float with sign). Synonyms like i, f, and r are supported.
    • Handle signs and exponents:
      • Use -s or --sign to consider + or - as part of a number.
      • Use --noexp to prevent exponential notation (e.g., 1e4) from being treated as a single number.
    • Locale-aware sorting: Use -l or --locale for locale-specific sorting (requires PyICU).
    # Example: Sort file paths in reverse order, filtering for numbers between 10 and 100
    natsort -p -r -f 10 100 file1.txt file2.txt file10.txt
    
    # Example: Sort entries from stdin split by null characters
    find . -print0 | natsort -z
  8. Identify and handle deprecated APIs

    main

    Several APIs were removed in version 6.0.0. To identify if your code is using deprecated features, run your script with the DeprecationWarning flag enabled:

    python -Wdefault::DeprecationWarning my-code.py

    Alternatively, set the PYTHONWARNINGS environment variable:

    export PYTHONWARNINGS="default::DeprecationWarning"
    python my-code.py

    Removed in 6.0.0:

    • number_type keyword argument
    • signed keyword argument
    • exp keyword argument
    • as_path keyword argument
    • py3_safe keyword argument
    • ns.TYPESAFE
    • ns.DIGIT
    • ns.VERSION
    • versorted()
    • index_versorted()
  9. Sort mixed types (int, float, str)

    main

    Unlike the built-in sorted() function, which raises a TypeError when comparing incompatible types like int and str, natsorted() can handle lists containing a mix of int, float, and str types.

    from natsort import natsorted
    
    a = ['4.5', 6, 2.0, '5', 'a']
    natsorted(a)
    # Output: [2.0, '4.5', '5', 6, 'a']
  10. Sort versions using natural sorting

    main

    While natsort does not explicitly parse versioning logic, most common versioning schemes (like MAJOR.MINOR, MAJOR.MINOR.PATCH, or YEAR.MONTH.DAY) work out-of-the-box with natsorted() because they follow natural numeric patterns.

    from natsort import natsorted
    
    a = ['version-1.9', 'version-2.0', 'version-1.11', 'version-1.10']
    natsorted(a)
    # Output: ['version-1.9', 'version-1.10', 'version-1.11', 'version-2.0']