Trivial bugfixes.
[realism.git] / utils.py
blob29d6a1e4132a2228ad756bcee2c13370ab470ee7
1 # This file is part of Realism, which is Copyright FunnyMan3595 (Charlie Nolan)
2 # and licensed under the GNU GPL v3. For more details, see LICENSE in the main
3 # Realism directory.
5 # This file is dual-licensed under the LGPL.
7 '''This module holds a few generic utilities that could be of use in many programs.
9 to_bool(value): converts a string to a boolean semantically, as for a config file.
10 any, all: Implementations of these standard functions for older versions of Python.'''
12 def to_bool(value):
13 '''Converts a string to a boolean semantically. Usage:
14 to_bool("tRuE") -> True
15 to_bool("no") -> False
16 to_bool("spam") -> raises ValueError
18 Acceptable values (case insensitive):
19 True: t, true, y, yes, on, enable, 1
20 False: f, false, n, no, off, disable, 0'''
21 false = ['f','false','n','no','off', 'disable', '0']
22 true = ['t','true','y','yes','on', 'enable', '1']
23 temp = str(value).strip().lower()
24 if temp in false:
25 return False
26 elif temp in true:
27 return True
28 else:
29 raise ValueError("Cannot parse boolean from input: %s" % value)
31 # Allows all and any to handle either one iterable object or a set of arguments.
32 def _arglist(*args):
33 '''Returns an iterable, either the sole argument passed to it or the entire argument tuple. Usage:
34 _arglist(a_list) -> a_list
35 _arglist(foo, bar, baz) -> (foo, bar, baz)
36 _arglist("hiya") -> ("hiya",)'''
37 from types import GeneratorType as generator
38 if len(args) == 1 and type(args[0]) in (list, tuple, generator):
39 return args[0]
40 else:
41 return args
43 def all(*args):
44 '''Legacy implementaiton of Python's all function. Returns true if all elements are true. Usage:
45 all(list_of_true_elements) -> True
46 all(True, True, True) -> True
47 all(True, False) -> False
48 all() -> True'''
49 AND = lambda a,b: a and b
50 return reduce(AND, _arglist(*args), True)
52 def any(*args):
53 '''Legacy implementation of Python's any function. Returns true if any element is true. Usage:
54 any(list_with_a_true_element) -> True
55 any(False, True, False) -> True
56 any(False, False) -> False
57 any() -> False'''
58 OR = lambda a,b: a or b
59 return reduce(OR, _arglist(*args), False)