[utils] Add try_get

To reduce boilerplate when accessing JSON
This commit is contained in:
Sergey M․ 2016-06-12 06:05:34 +07:00
parent 2c3322e36e
commit 329ca3bef6
No known key found for this signature in database
GPG key ID: 2C393E0F18A9236D

View file

@ -1901,6 +1901,16 @@ def dict_get(d, key_or_keys, default=None, skip_false_values=True):
return d.get(key_or_keys, default) return d.get(key_or_keys, default)
def try_get(src, getter, expected_type=None):
try:
v = getter(src)
except (AttributeError, KeyError, TypeError, IndexError):
pass
else:
if expected_type is None or isinstance(v, expected_type):
return v
def encode_compat_str(string, encoding=preferredencoding(), errors='strict'): def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
return string if isinstance(string, compat_str) else compat_str(string, encoding, errors) return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)