Debian Codegraph @

mediafile/utils/type_conversion.py

raw
1 import re
2
3
4 def safe_cast(out_type, val):
5 """Try to covert val to out_type but never raise an exception.
6
7 If the value does not exist, return None. Or, if the value
8 can't be converted, then a sensible default value is returned.
9 out_type should be bool, int, or unicode; otherwise, the value
10 is just passed through.
11 """
12 if val is None:
13 return None
14
15 if out_type is int:
16 if isinstance(val, int) or isinstance(val, float):
17 # Just a number.
18 return int(val)
19 else:
20 # Process any other type as a string.
21 if isinstance(val, bytes):
22 val = val.decode("utf-8", "ignore")
23 elif not isinstance(val, str):
24 val = str(val)
25 # Get a number from the front of the string.
26 match = re.match(r"[\+-]?[0-9]+", val.strip())
27 return int(match.group(0)) if match else 0
28
29 elif out_type is bool:
30 try:
31 # Should work for strings, bools, ints:
32 return bool(int(val))
33 except ValueError:
34 return False
35
36 elif out_type is str:
37 if isinstance(val, bytes):
38 return val.decode("utf-8", "ignore")
39 elif isinstance(val, str):
40 return val
41 else:
42 return str(val)
43
44 elif out_type is float:
45 if isinstance(val, int) or isinstance(val, float):
46 return float(val)
47 else:
48 if isinstance(val, bytes):
49 val = val.decode("utf-8", "ignore")
50 else:
51 val = str(val)
52 match = re.match(r"[\+-]?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)", val.strip())
53 if match:
54 val = match.group(0)
55 if val:
56 return float(val)
57 return 0.0
58
59 else:
60 return val