From 62add955f99e96a89bc27002675eb99f5182185d Mon Sep 17 00:00:00 2001 From: jaseg Date: Mon, 25 Dec 2017 13:16:58 +0100 Subject: Refactor node_cast_value to use large if/elif instead of dict lookup --- mpv.py | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/mpv.py b/mpv.py index 19fccae..cd3fc3b 100644 --- a/mpv.py +++ b/mpv.py @@ -196,18 +196,31 @@ class MpvNode(Structure): @staticmethod def node_cast_value(v, fmt=MpvFormat.NODE, decoder=identity_decoder): - return { - MpvFormat.NONE: lambda v: None, - MpvFormat.STRING: lambda v: decoder(v.string), - MpvFormat.OSD_STRING: lambda v: v.string.decode('utf-8'), - MpvFormat.FLAG: lambda v: bool(v.flag), - MpvFormat.INT64: lambda v: v.int64, - MpvFormat.DOUBLE: lambda v: v.double, - MpvFormat.NODE: lambda v: v.node.contents.node_value(decoder) if v.node else None, - MpvFormat.NODE_ARRAY: lambda v: v.list.contents.array_value(decoder) if v.list else None, - MpvFormat.NODE_MAP: lambda v: v.map.contents.dict_value(decoder) if v.map else None, - MpvFormat.BYTE_ARRAY: lambda v: v.byte_array.contents.bytes_value() if v.byte_array else None, - }[fmt](v) + if fmt == MpvFormat.NONE: + return None + elif fmt == MpvFormat.STRING: + return decoder(v.string) + elif fmt == MpvFormat.OSD_STRING: + return v.string.decode('utf-8') + elif fmt == MpvFormat.FLAG: + return bool(v.flag) + elif fmt == MpvFormat.INT64: + return v.int64 + elif fmt == MpvFormat.DOUBLE: + return v.double + else: + if not v.node: # Check for null pointer + return None + if fmt == MpvFormat.NODE: + return v.node.contents.node_value(decoder) + elif fmt == MpvFormat.NODE_ARRAY: + return v.list.contents.array_value(decoder) + elif fmt == MpvFormat.NODE_MAP: + return v.map.contents.dict_value(decoder) + elif fmt == MpvFormat.BYTE_ARRAY: + return v.byte_array.contents.bytes_value() + else: + raise TypeError('Unknown MPV node format {}. Please submit a bug report.'.format(fmt)) class MpvNodeUnion(Union): _fields_ = [('string', c_char_p), -- cgit