diff options
author | Seth M Morton <seth.m.morton@gmail.com> | 2016-05-03 22:30:37 -0700 |
---|---|---|
committer | Seth M Morton <seth.m.morton@gmail.com> | 2016-05-03 22:30:37 -0700 |
commit | 22ad659ed844cbdd7d179b74acc7b25d135da73f (patch) | |
tree | 29f97e07f4f2ca2a60690f433910a63c942f88b4 | |
parent | 987ad2bda796a72b402573dbdabeba01f49b893a (diff) | |
download | natsort-22ad659ed844cbdd7d179b74acc7b25d135da73f.tar.gz |
Improved chain_functions speed.
This new method essentially hard-codes the chained function
using eval.
-rw-r--r-- | natsort/utils.py | 17 | ||||
-rw-r--r-- | test_natsort/test_utils.py | 5 |
2 files changed, 16 insertions, 6 deletions
diff --git a/natsort/utils.py b/natsort/utils.py index 67be2f6..c74d340 100644 --- a/natsort/utils.py +++ b/natsort/utils.py @@ -28,6 +28,7 @@ from natsort.locale_help import locale_convert_function, groupletters from natsort.compat.pathlib import PurePath, has_pathlib from natsort.compat.py23 import ( py23_str, + py23_range, py23_map, py23_filter, PY_VERSION, @@ -310,12 +311,16 @@ def chain_functions(functions): 17 """ - def func(x, _functions=functions): - output = x - for f in _functions: - output = f(output) - return output - return func + if not functions: + return lambda x: x + elif len(functions) == 1: + return functions[0] + else: + func = 'x' + for i in py23_range(len(functions)): + func = '_f[{:d}]({})'.format(i, func) + func = 'lambda x, _f=functions: ' + func + return eval(func, None, {'functions': functions}) def _do_decoding(s, encoding): diff --git a/test_natsort/test_utils.py b/test_natsort/test_utils.py index 6bb5818..f7aeff2 100644 --- a/test_natsort/test_utils.py +++ b/test_natsort/test_utils.py @@ -155,6 +155,11 @@ def test_chain_functions_is_a_no_op_if_no_functions_are_given(): assert chain_functions([])(x) is x +def test_chain_functions_does_one_function_if_one_function_is_given(): + x = '2345' + assert chain_functions([len])(x) == 4 + + def test_chain_functions_combines_functions_in_given_order(): x = 2345 assert chain_functions([str, len, op_neg])(x) == -len(str(x)) |