[portland] introspecting method signatures

John Hampton pacopablo at pacopablo.com
Wed Oct 22 23:08:38 CEST 2008

Jeff Schwaber wrote:
> The closest I've found is func.func_code.co_varnames, which is a list
> of variables in the signature, but it doesn't have default arguments
> or mark any which are * or **. Anybody know the right way to do this,
> or am I barking up the wrong tree? The # do something is what I'm
> after.

Sounds like you want decorators.  They are present in Python >=2.4.

Simplistic example:

def timefunc(fn):
     def wrapper(*args, **kwargs):
         st = time.time()
         val = fn(*args, **kwargs)
         print('Elapsed time: %0.2f' % (time.time() - st))
         return val
     return wrapper

So you can use this function to decorate any other function and it will 
time the decorated function.  (Note, there are better ways to profile 
your code, etc.)

def my_new_func(param, param1=None):
     print("This is timed!  param: %s, param1: %s" %
           (str(param), str(param1)))

my_new_func(1, param1='bar')

There are some decent tutorials on the intertubes regarding decorators. 
Google is your friend.


More information about the Portland mailing list