Mangle function name with decorator?

andrew cooke andrew at
Tue Mar 17 18:54:24 CET 2009

ah, ok.  then yes, you can do that with decorators.  you'd need hash
tables or something similar in a metaclass.  then the decorator would take
the given function, stick it in the appropriate hash table, and return a
function that does the dispatch (ie at run time does the lookup from the
hash table) (you'd only want to set the function once once, so it would
need to check the function wasn't already defined).  also, the decorator
would have one name and get/post etc would be an argument.

this is all documented in the docs and peps, although it's very spread
around.  you might look at the code for the property decorator - it's not
doing what you want, but it's an interesting non-trivial example that's


Adam wrote:
> Thanks, Andrew.  I'm trying to accomplish something with a
> metaprogramming flavor, where, for the convenience of the programmer
> and the clarity of code, I'd like to have a decorator or some other
> mechanism do twiddling behind the scenes to make a class do something
> it wouldn't normally do.
> Here's a less-obfuscated exmaple:  I want to build a framework for
> creating MVC web applications in Python (I know, I know, there's
> already 2^1bazillion of them) where a controller class can have
> methods that respond to the same action but for different HTTP verbs:
> class foo_controller(Controller):
>     @GET
>     def new(self):
>         # Display the form to create a new foo
>     @POST
>     def new(self):
>         # Receive a form post with new foo data in it
> The Controller class will do all of the work behind the scenes to
> makes sure that the correct method is called at run-time, but for the
> sake of the programmer, I'd like to supply a clear, friendly syntax
> like this.  Without a little metaprogramming magic, last-in-wins, and
> only the second version of foo will end up in the class, so I'd like
> to mangle the names to something that will result in a unique
> attribute name and that the Controller class can work with behind the
> scenes to do the right thing at run time.
> So, Python experts, am I completely barking up the wrong tree here?
> --

More information about the Python-list mailing list