Metaclass discussons

Pedro Werneck pedro.werneck at bol.com.br
Sun Aug 24 08:57:21 EDT 2003


Hi, 

On Fri, 22 Aug 2003 16:30:39 -0300
Gustavo Niemeyer <niemeyer at conectiva.com> wrote:

> Without yet considering interpreter hacks, that's what I had as a
> first solution (a very limited one, I must admit):
> 
> class M(type): pass
> __metaclass__ = M
> class object:
>     __metaclass__ = M
> execfile("somemodule.py", globals(), locals())

There are some problems with this approach. It's tricky to work with
packages using execfile and it doesn't work with byte-compiled files.

Yet with the same idea (executing it on a hacked context) I tried
something like this...

---

class MetaKlass(type): pass
__builtin__.object = MetaKlass("object", (), {"__slots__":[]})

somemodule = types.ModuleType("somemodule")
somemodule.__file__ = "somemodule.py"

data = open("somemodule.py").read()
code = compile(data, "somemodule.py", "exec")

somemodule.__dict__["__metaclass__"] = MetaKLass
exec code in somemodule.__dict__

--

Which is essentially the same, but more "low-level".

As the discussion was about new import hooks to impose metaclass on
existing modules, I wrote a simple module for it, available in
http://alpha.linuxmag.com.br:8080/python/Members/werneck/mop.tar.bz2

Any ideas ???


Pedro





More information about the Python-list mailing list