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

2020年11月23日 12:09:36 -0800

On Tue, Nov 24, 2020 at 7:00 AM Ethan Furman <[email protected]> wrote:
>
> 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.
I think the implication is that, since all the successful if
statements go into returns, you can leave off the "else" and just put
the "raise" immediately. It's a special case that applies ONLY to
situations where the pattern matching is the entire purpose of the
function.
ChrisA
_______________________________________________
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/5XN74AAVN2MITMG574LNCDBZJCP2LN76/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to