-1

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
        }[clazz]

setFieldToInt and setFieldToDatetime are methods inside context class.

java_mouse
  • 2,069
  • 4
  • 21
  • 30

2 Answers2

1

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? .

Community
  • 1
  • 1
turbulencetoo
  • 3,447
  • 1
  • 27
  • 50
0

More briefly. The code presented is expecting the class of some object as a parameter poorly named as clazz. It's then using that class as a dictionary key. They're essentially trying to accept two different types and call a method on the object type.

class is a keyword in Python. The author of the code you show chose to use a strange spelling instead of a longer snake_case parameter name like obj_class. The parameters really should have been named obj, obj_class Or instance, instance_class

Even better, the class really need not be a separate parameter.

uchuugaka
  • 12,679
  • 6
  • 37
  • 55