Metaclass with name overloading.

Alex Martelli aleaxit at yahoo.com
Mon Sep 27 09:27:31 EDT 2004


Carlos Ribeiro <carribeiro at gmail.com> wrote:
   ...
> No, you can't, and it's not just a parser issue. Python uses direct C
> calls to the native dict type. It's hard coded, and I don't see any
> obvious or easy way to override it except by rewriting all such code.

The STORE_NAME used within the code object to which the class body gets
compiled is quite ready for a non-native-dict f_locals of the frame.
The problem is how to get your own favourite object into that f_locals
in the first place, and THAT one is hard -- can't think of any way...

> The metaclass receives the dictionary after all declarations were
> collected, and then it's too late to act upon it.

Yep, far too late.  You'd have to somehow tweak the CALL_FUNCTION
bytecode that's compiled as part of the class statement, so that it
makes a frame whose f_locals is some strange object of your choice.

> Now that we're talking about it, I would like to discuss how this type
> of hack could possibly be done in a future version of Python (probaly
> Python 3.0, I don't think it's anywhere close to possible for Python
> 2.x).

I think it might be quite feasible in 2.5 (too late for 2.4).


> 1) One such idea is to provide the metaclass with a __dict__ factory.

If you go that route, then it may indeed require changes too deep for
2.5 or 2.anything.  The metaclass gets determined later, at the time
CALL_FUNCTION executes the metaclass ain't in play yet.

> By using a user-defined dict, we would still use the default dict most
> of the time without any noticeable performance hit, but would be able
> to change the guts of the class declaration system whenever needed.

Yeah, but if you make it a metaclass's job, then you're indeed asking
for deep changes from today's architecture.

> 2) Another (crazy) idea is to have the possibility to declare
> anonymous class members, such as in:
> 
> class MyClass:
>     """the first anonymous member is the doc string""" 
>     """the second anonymous member is __anon__[0]"""
>     1.5 # __anon__[1] = 1.5
> 
> By anonymous members, I mean anything that is not a def, a nested
> class, or a value that wasn't assigned or bound to name. That's would
> be nice to have too :-)

Maybe, and maybe not, but it would not help in the least with dealing
with two def's for the same name, as the OP wanted.

One thing that might work: have a sys._set_locals_factory(...) which
lets you change (maybe per-thread...?) how a frame's f_locals are made.


Alex



More information about the Python-list mailing list