On 11/23/20 11:06 AM, Larry Hastings wrote:
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".
Without the "else" errors will pass silently.
And you can change all your "elif"s into "if"s too.
On average, doubling your comparisons and therefore becoming slower.
Now your "isinstance" version is 35 lines. Shorter than the pattern matching version
But without error checking.
roughly the same speed,
works in current Python, eminently readable to anybody conversant in current Python. A very reasonable solution to
See above comment about becoming slower. the problem. Agreed. But (subjectively, of course) not as elegant as the match version, and deteriorates rapidly as complexity increases.
There should be one--and preferably only one--obvious way to do it,
But that is not a hard and fast rule or we wouldn't have decorators (zero lines saved), the "with" statement (two lines saved), and four different ways spanning three different protocols to write an iterator [1]. -- ~Ethan~ [1] https://stackoverflow.com/questions/19151/build-a-basic-python-iterator/7542...