Spot any errors? let me know, but Unleash your pedant politely please.

Sunday, 17 May 2009

Python: count of parameters in a function

I recently had a problem with a that class had several ways to populate one of its instance variables. An instance method was called in each case, either with a parameter, (using the method provided by the class), or without a parameter, (in the case of the same method overridden in a subclass). I've since realised that there was a simpler/better way to achieve this, but no matter, Python allowed me to figure out which one to call by being able to count the parameters in the method, and then call

import inspect

def parametersInMethod(method):
    return len(inspect.getargspec(method)[0])

Allowed me to do this...

if parametersInMethod(self.populateInstanceVariable) == 0:
    self.populateInstanceVariable()
else:
    self.populateInstanceVariable(withValue)

This give a little insight into 'inspect' and also shows how methods being objects allow them to be passed as parameters into functions.

No comments:

Post a Comment