Metaclass with name overloading.

Alex Martelli aleaxit at yahoo.com
Mon Sep 27 16:43:54 EDT 2004


Carlos Ribeiro <carribeiro at gmail.com> wrote:

> On Mon, 27 Sep 2004 19:11:14 +0200, Alex Martelli <aleaxit at yahoo.com> wrote:
> > so, class blop doesn't really have an 'f' (it does have it in the
> > __dict__, but it's a dummy '_ignore_method' entry with a suitable custom
> > metaclass would easily prune!-) but has __overloaded__f__0 and
> > __overloaded__f__1 methods (which, again, a suitable custom metaclass
> > could do whatever wonders with!-).
> 
> The decorator could play it safe, and at the same time, return
> something like the original poster expects. Upon decoration the

I think it's a better architecture to have the metaclass process all the
overloads, and until the metaclass runs, leave a marker-value for the
name.  Otherwise, uncaught errors are just too likely.

> following would happen:
> 
> 1) store the newly declared object in the list __overloaded__<$name>.

So far, so NP -- I did name mangling period, but name mangling plus
indexing is fine too.

> 2) return a new object (to be bound to the <$name>), where
> <$name>.__call__ would return __overloaded__<$name>[-1]; and
> f.__iter__ would return an iterator for all declaration in the order
 > they appear.

I think you'll have more nondiagnosable error cases this way.  You can
add more error checking to the very simple decorator I posted, of
course.  The key issue to catch is the error whereby some occurrences of
the name are correctly decorated '@ overload' and others aren't.
Decorator and metaclass working together can do it, but if you don't
ensure the metaclass runs at the end (and it seems to me your approach
wouldn't) then such errors towards the end would stay uncaught.

> 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?

Do it in the metaclass.  Unless the metaclass was indispensable (and it
is) you could use custom descriptors, too; Raymond Hettinger has a nice
essay on descriptors that shows how to write your own custom ones.


Alex



More information about the Python-list mailing list