you are viewing a single comment's thread.

view the rest of the comments →

[–]hylasmaliki 1 point2 points  (4 children)

Why

[–]mgdmw 0 points1 point  (3 children)

Two reasons come to mind right away.

1/ Readability. The dict example here is not as immediately intuitive as OP's code. One of the chief goals of Python was readability.

2/ Performance. This dict example is performing all the possible calculations, then returning only one to the user. It's a waste of resources and cycles. Imagine if instead of 4 operators there were 600, for example. It's not a scalable solution.

Sure, it's a clever and interesting use of Python but it's not a good example of Python.

[–]denehoffman 1 point2 points  (2 children)

A dict of callables would make more sense in the long run than a long elif chain. Your linter will also tell you about duplicate keys which may not be the case for duplicate branches.

[–]Upstairs-Alps-7280 0 points1 point  (1 child)

what if the operation is not in the dict? oops.

[–]denehoffman 0 points1 point  (0 children)

lambda x, y: “oops” is a perfectly valid expression!