Mangle function name with decorator?

Adam adam.crossland at gmail.com
Wed Mar 18 16:31:36 CET 2009


On Mar 18, 11:11 am, "R. David Murray" <rdmur... at bitdance.com> wrote:
> I don't have any wisdom on the metaclass/decorator stuff, but what
> about slightly reformulating the interface?  Instead of having the
> programmer type, eg:
>
>     @GET
>     def foo(self): pass
>
>     @POST
>     def foo(self): pass
>
> have them type:
>
>     def GET_foo(self): pass
>     def POST_foo(self): pass
>
> It's even one less character of typing (the <cr> :)
>
> --
> R. David Murray          http://www.bitdance.com

David, would you believe that I just posted about this very idea,  It
doesn't seem to have shown up yet, though.  This idea works from the
perspective of being trivially easy to implement.  I can easily write
a metaclass that looks in the namespace for methods with names that
start with GET_or POST_, or I can override __getattribute__ to do the
look up that way.  However, there are a couple of weaknesses that I
see with this approach.

First, from a purely aesthetic point of view, prepending the desired
verb to the method name just looks a bit ugly.  Also, it makes it
difficult to deal elegantly with avoiding duplicating code when one
piece of logic should dealing with more than one verb.  So, if I want
to have one method that works for GET and POST, I can do this:

def GET_foo(self):
    # Do stuff for GET

def POST_foo(self):
    return self.GET_foo()

but then I feel like I am cluttering my controller code with unneeded
functions when writing
@GET
@POST
def foo(self):
   # Blah blah blah

would be so much neater.

Or, I could allow method signatures like:
def GET_POST_foo(self):
   # Blah, blah, blah

But now my code to parse and manipulate or do lookups on methods names
is much more complicated.  Also, it introduces difficult ambiguities
in the case that an action of the controller has the same name as an
HTTP Verb.  These ambiguities can be coded around, but doing so makes
the code more-and-more crufty and prone to breakage.  I don't want to
build too much of a Rube Goldberg machine here, right?  What I really
want to do is use Python's metaprogamming facilities to provide an
elegant solution to a problem.  Unfortunately, I really don't think
that it is going to work out in any way that is really satisfying.



More information about the Python-list mailing list