[portland] introspecting method signatures

Jeff Rush jeff at taupro.com
Thu Oct 23 13:39:25 CEST 2008


Jeff Schwaber wrote:
> On Wed, Oct 22, 2008 at 2:09 PM, Jesse Hallett <hallettj at gmail.com> wrote:
>>
>> I found this link with code for aliasing methods. You can probably alias the
>> original method, then override the original method name with a new method,
>> and call the aliased method from the new method.
>>
>> http://waimangu.typepad.com/notepad/2006/12/usrbinenv_pytho.html
>>
>> I haven't tried the code though; so I can't guarantee that it works.
> 
> Yeah, I'm not sure exactly why it's working and other things I've
> tried aren't, but that looks like what I'm trying to do.
> 
> Decorators, as John Hampton suggested, may also be a good choice,
> because they're pretty clear syntax.

Regardless of your approach, go read up about the 'inspect' module in the
Python stdlib for tips on how to introspect the signature of a callable.  It
does all the heavy lifting that you're trying to do with the
func.func_code.co_varnames.

Another useful piece of code for study is the 'decorator' module in the
Cheeseshop.  It uses signature introspection to hide itself and minimize
impact on the wrapped function.

Grab its source using:

  easy_install --editable -b . decorator

and look in the subdirectory 'decorator', or install it for use:

  easy_install decorator

What you're doing, re registering functions in a global list, is one of the
three things possible with a conventional Python decorator.  The other two are
to (2) adjust attributes of the wrapped function and (3) intercept the call
and return phases of execution.  The thing to remember about decorators is
that they are called at "function definition time", not "function invocation
time".

I go into this a bit in a presentation I created for the recent PyArkansas
regional conference.  You can find my slides/handouts at:

https://dfwpython.org/repo/Presentations/2008-10-04-PyArkansas-PythonConcepts/

-Jeff


More information about the Portland mailing list