3.1. natsort_keygen()

natsort.natsort_keygen(key=None, number_type=<type 'float'>, signed=None, exp=None, as_path=None, py3_safe=None, alg=0)

Generate a key to sort strings and numbers naturally.

Generate a key to sort strings and numbers naturally, not lexicographically. This key is designed for use as the key argument to functions such as the sorted builtin.

The user may customize the generated function with the arguments to natsort_keygen, including an optional key function which will be called before the natsort_key.

Parameters:

key : callable, optional

A key used to manipulate the input value before parsing for numbers. It is not applied recursively. It should accept a single argument and return a single value.

number_type : {None, float, int}, optional

Depreciated as of version 3.5.0 and will become an undocumented keyword-only argument in 4.0.0. Please use the alg argument for all future development. See ns class documentation for details.

signed : {True, False}, optional

Depreciated as of version 3.5.0 and will become an undocumented keyword-only argument in 4.0.0. Please use the alg argument for all future development. See ns class documentation for details.

exp : {True, False}, optional

Depreciated as of version 3.5.0 and will become an undocumented keyword-only argument in 4.0.0. Please use the alg argument for all future development. See ns class documentation for details.

as_path : {True, False}, optional

Depreciated as of version 3.5.0 and will become an undocumented keyword-only argument in 4.0.0. Please use the alg argument for all future development. See ns class documentation for details.

py3_safe : {True, False}, optional

Depreciated as of version 3.5.0 and will become an undocumented keyword-only argument in 4.0.0. Please use the alg argument for all future development. See ns class documentation for details.

alg : ns enum, optional

This option is used to control which algorithm natsort uses when sorting. For details into these options, please see the ns class documentation. The default is ns.FLOAT.

Returns:

out : function

A wrapped version of the natsort_key function that is suitable for passing as the key argument to functions such as sorted.

Examples

natsort_keygen is a convenient waynto create a custom key to sort lists in-place (for example). Calling with no objects will return a plain natsort_key instance:

>>> a = ['num5.10', 'num-3', 'num5.3', 'num2']
>>> b = a[:]
>>> a.sort(key=natsort_key)
>>> b.sort(key=natsort_keygen())
>>> a == b
True

The power of natsort_keygen is when you want to want to pass arguments to the natsort_key. Consider the following equivalent examples; which is more clear?

>>> a = ['num5.10', 'num-3', 'num5.3', 'num2']
>>> b = a[:]
>>> a.sort(key=lambda x: natsort_key(x, key=lambda y: y.upper(),
...        signed=False))
>>> b.sort(key=natsort_keygen(key=lambda x: x.upper(), signed=False))
>>> a == b
True