Metaclass with name overloading.

Carlos Ribeiro carribeiro at gmail.com
Mon Sep 27 23:44:54 CEST 2004


On Mon, 27 Sep 2004 21:23:14 GMT, Lenard Lindstrom <len-1 at telus.net> wrote:
> Carlos Ribeiro <carribeiro at gmail.com> writes:
> > <sample code snip>
> > The problem is that the methods were not bound to the instance. Adding
> > individual names to each method won't work, because it'll not bind the
> > references stored in the overload_list. I thought about using a
> > closure or curry type of solution, but that's something that I still
> > don't understand very well. Any tips?
> > 
> Here is my take on decorator overloaded. I implement OverloadedFunction
> as a descriptor. It supports method binding.

That's what I was missing. I've read about descriptors last week, but
didn't had the time to get a hand at it. It's interesting. My
development machine is still using 2.3 -- I don't know if this
descriptor fancy stuff would work here... *btw, that's why my original
snippet didn't use the new syntax to call the decorator).

I think that this code is now Cookbook-ready. Any comments?
 
> import sys
> 
> class OverloadedFunction(object):
>     class BoundMethod:
>         def __init__(self, functions, instance, owner):
>             self.bm_functions = functions
>             self.bm_instance = instance
>             self.bm_owner = owner
>         def __getitem__(self, index):
>             return self.bm_functions[index].__get__(self.bm_instance,
>                                                     self.bm_owner)
>     def __init__(self):
>         self.of_functions = []
>     def addFunction(self, func):
>         self.of_functions.append(func)
>     def __get__(self, instance, owner):
>         return self.BoundMethod(self.of_functions,
>                                 instance,
>                                 owner)
> 
> def overloaded(func):
>     try:
>         olf = sys._getframe(1).f_locals[func.__name__]
>     except KeyError:
>         olf = OverloadedFunction()
>     olf.addFunction(func)
>     return olf
> 
> # Test case:
> class blob:
>     def __init__(self, member):
>         self.member = member
>     @overloaded
>     def f(self):
>         return "f 0: member=%s" % self.member
>     @overloaded
>     def f(self, s):
>         return "f 1: member=%s, s=%s" % (self.member, s)
> 
> b=blob("XXX")
> print b.f[0]()
> print b.f[1]("Yet another f")
> 
> ---- Output ---
> 
> f 0: member=XXX
> f 1: member=XXX, s=Yet another f
> 
> 
> Lenard Lindstrom
> <len-l at telus.net>


-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list