1"""isort/natural.py.
2
3Enables sorting strings that contain numbers naturally
4
5usage:
6    natural.nsorted(list)
7
8Copyright (C) 2013  Timothy Edmund Crosley
9
10Implementation originally from @HappyLeapSecond stack overflow user in response to:
11   https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
12
13Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
14documentation files (the "Software"), to deal in the Software without restriction, including without limitation
15the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
16to permit persons to whom the Software is furnished to do so, subject to the following conditions:
17
18The above copyright notice and this permission notice shall be included in all copies or
19substantial portions of the Software.
20
21THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
22TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
24CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25OTHER DEALINGS IN THE SOFTWARE.
26
27"""
28import re
29
30
31def _atoi(text):
32    return int(text) if text.isdigit() else text
33
34
35def _natural_keys(text):
36    return [_atoi(c) for c in re.split(r'(\d+)', text)]
37
38
39def nsorted(to_sort, key=None):
40    """Returns a naturally sorted list"""
41    if key is None:
42        key_callback = _natural_keys
43    else:
44        def key_callback(item):
45            return _natural_keys(key(item))
46
47    return sorted(to_sort, key=key_callback)
48