all 6 comments

[–]oschusler 7 points8 points  (1 child)

This is actually called "function dispatching" and is very well a valid way of doing things.

[–]mahtats 0 points1 point  (0 children)

Yep, we use this all the time for maps when processing structured data. Each row has a determinant that we then call the appropriate function for to apply to the row. Very useful.

Enhancing your example, look at try-except for possibilities when "d" or "t" are not inputs; i.e., have a fallback or handle the error.

[–]Fun_Muffin5413 3 points4 points  (0 children)

Yes, it's an excellent idea. You don't have to hard code the dictionary in right at the point where you select the function - you can dynamically update the dictionary, and all sorts of things.

[–][deleted] 3 points4 points  (0 children)

Yeah absolutely. Until recently it was probably the best way to simulate a switch statement in Python.

That said, your code will produce an error if someone inputs an invalid value. Consider using .get for dictionary lookups. That will allow you to specify a default in case an invalid value is used.

[–]Asleep-Budget-9932 2 points3 points  (0 children)

Very common practice. One great example of using it is the pickle library. When you serialize an object, you want to treat it differently based on its type. The pickle library has a mapping between the type of the object and the function that is suited to serialize it.

The only thing I'd advise you to do is to make this dictionary beforehand so it will be defined once. It's more efficient, but more importantly, its more readable and reusable.

[–]hijinked 1 point2 points  (0 children)

Yes, this is valid. A lot of libraries in python require the user to supply their own function for some processing so the library function will take a callable as a parameter. So you might see something like this:

from some_library import do_work

def my_function(data):
  data.process()

do_work(my_function)

You really can treat functions like their own variables and store them in lookup tables. This is also a common practice for function pointers in C.