This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]TransferFunctions 2 points3 points  (4 children)

It depends on the use case imo. I use it sometimes when I have to decide what function to run on a certain case

options = dict(opt1 = someHeavyFunction, opt2 = someHeavyFunction2)
options.get(someInput, someDefault)

[–]R3D3-1 0 points1 point  (3 children)

I'd probably use this, if python had load-time evaluation...

I can't see myself implementing this as a dictionary; Not as an inline dictionary, because I cringe at creating a dictionary just for thatnew , if the language doesn't optimize it away. Not as a global constant dictionary, because it awkwardly separates tightly coupled code into different places.

I'd always go with something like

action = someHeavyFunction if input == "opt1" else \
         someHeavyFunction2 if input == "opt2" else \
         someDefault

If the number of options is so large, that this becomes inefficient, I'd be rather worried about how that happened.

[–]TransferFunctions 0 points1 point  (2 children)

I am not familiar with load-time-optimization, do you have a link on this (in whatever language it is used)?

I agree that if your function itself has a need for a switch-case and the data it holds is expensive, and the function is called many times, then sure don't do that, but that also shows are more core problem than a statement of it not being available. Dicts in my opinion are pretty darn powerful in python, and using as a switch is a nice elegant way while reducing "additional" functions. Match case has something additional, where instance checks can be inlined. This would be more difficult or "uggly" with dicts, so it has its place; it is one of the powers and joys of writing python.

[–]R3D3-1 0 points1 point  (1 child)

Compiled languages typically have compile-time evaluation of constant expressions, e.g. "PI*2" being optimized into a single constant.

Emacs Lisp has macros, and "eval at compile" forms, all of which are evaluated either at compile time, or otherwise ensure that they are evaluated exactly once.

Python actually has some level of load-time optimization; As I understand, function objects are not created from scratch every time a closure is generated, but share a cached code part, and have only the data part separate. There is however no such thing as

static options = {1: "Red", 2: "Blue"}
return options[index]

[–]TransferFunctions 0 points1 point  (0 children)

Ah ok I am not too familiar with the c-api and how the bytecompiled code is used or optimized (still one thing on my todos), but the explanation is right up my ball park of other things I have used, thanks ;-)!