def extract_elem_v2(elem_name):

    def key_extractor(obj):
        dct = obj if isinstance(obj, dict) else obj.__dict__
return dct[elem_name]
return key_extractor
Sorting a heterogeneous list of objects in Python