[Python-Dev] Re: Advantages of pattern matching - a simple comparative analysis

2020年11月23日 11:10:28 -0800

On 11/23/20 8:15 AM, Brian Coleman wrote:
def process(root_node: Node):
 def process_node(node: Node):
 if isinstance(node, StringNode):
 return node.value
 elif isinstance(node, NumberNode):
 return float(node.value)
 elif isinstance(node, ListNode):
 return [process_node(child_node) for child_node in node.children]
 elif isinstance(node, DictNode):
 return {key: process_node(child_node) for key, child_node in 
node.children}
 else:
 raise Exception('Unexpected node')
You don't need the "else". And you can change all your "elif"s into "if"s too. Now your "isinstance" version is 35 lines. Shorter than the pattern matching version, roughly the same speed, works in current Python, eminently readable to anybody conversant in current Python. A very reasonable solution to the problem.
There should be one--and preferably only one--obvious way to do it,
//arry/
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/UWWSPCW7WBYKVXG2VQWWHGXRN6SH2HM6/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to