Sunday, July 22, 2007

Python: Mapping arguments to their default values

Using inspect.getargspec or the getargspec implemention in my previous post, we can build a dictionary mapping a callable's argument names to their default values:
def getargmap(obj, default=None):
"""Get dictionary mapping callable's arguments to their
default values

Arguments without default values in the callable's argument
specification are mapped to the value given by the default
spec = getargspec(obj)
argmap = dict.fromkeys(spec[0], default)
argmap.update(zip(spec[0][-len(spec[3]):], spec[3]))
return argmap

No comments: