java_mouse java_mouse - 8 months ago 67
Python Question

returning functions from a method in python

I have tried looking into the documentation and google search , but I am unable to find out the significance of the [clazz] at the end of method. Could someone help me understand the meaning of the [clazz] at the end of the method? Thanks.

def get_context_setter(context, clazz):
return {
int: context.setFieldToInt,
datetime: context.setFieldToDatetime

setFieldToInt and setFieldToDatetime are methods inside context class.


This function returns one of two things. It returns either context.setFieldToInt or context.setFieldToDatetime. It does so by using a dictionary as what would be a switch statement in other programming languages.

It checks whether clazz is a reference to the class int or a reference to the class datetime, and then returns the appropriate method.

It's identical to this code:

def get_context_setter(context, clazz):
    lookup_table = {int: context.setFieldToInt,
                    datetime: context.setFieldToDatetime
    context_function = lookup_table[clazz] # figure out which to return
    return context_function

Using a dict instead of a switch statement is pretty popular, see Replacements for switch statement in Python? .