aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSergey M․ <dstftw@gmail.com>2016-06-12 06:05:34 +0700
committerSergey M․ <dstftw@gmail.com>2016-06-12 06:05:34 +0700
commit329ca3bef695bff011ed9b2d5f03e1331bf5bf0f (patch)
tree0d644ffdb698d623a0af4354d1ac171c26b84804
parent2c3322e36ef23eb0566b820dd8e8711de20ed963 (diff)
[utils] Add try_get
To reduce boilerplate when accessing JSON
-rw-r--r--youtube_dl/utils.py10
1 files changed, 10 insertions, 0 deletions
diff --git a/youtube_dl/utils.py b/youtube_dl/utils.py
index 0acbd67de..c8308ba3a 100644
--- a/youtube_dl/utils.py
+++ b/youtube_dl/utils.py
@@ -1901,6 +1901,16 @@ def dict_get(d, key_or_keys, default=None, skip_false_values=True):
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'):
return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)