[Tutor] Introspect function or class' required arguments

Luis N globophobe at gmail.com
Fri Dec 14 03:08:11 CET 2007


Is there a way to introspect a function or class' required arguments,
particularly keyword arguments?

I can easily use a dictionary since it is my own function that I wish
to introspect. I haven't tested the below code yet, but e.g.

obj = getattr(self, 'obj')()
preprocessors = {'Card':[{'obj_attr':'mastery',
                          'call':mastery,
                          'args_dict':['front', 'back']}
                         ]
                 }
obj_preprocessors = preprocessors.get(obj.__name__, None)
if obj_preprocessors:
    for preprocessor in obj_preprocessors:
        function_name = preprocessor['call'].__name__
        args_dict = {}
        for arg in preprocessor['args_dict']:
            if self.query_dict.has_key(arg):
                args_dict[preprocessor[arg]] = self.query_dict.get(arg)
            else:
                self.error = 'Required argument %s omitted for
function %s' % (arg, function_name)
                break
        if not hasattr(self, error):
            try:
                setattr(obj, preprocessor['obj_attr'],
preprocessor['call'](args_dict))
            except:
                self.error = 'Preprocessor %s failed.' % function_name
        else:
            break


More information about the Tutor mailing list