[Python-Dev] Monkeypatching idioms -- elegant or ugly? (original) (raw)

nathan binkert nate at binkert.org
Thu Jan 31 21:33:23 CET 2008


Have you tried this? I believe it doesn't even work; types defined in C++ are supposed to be immutable. Try adding a new method to list or dict. I noticed that and I was trying to figure out if I could create a new metatype which would add a dict and a method (called add_method or something like that) that could be used as a decorator for monkeypatching. I was partly using this as an exercise to learn more about the Python internals and I'm probably going down a rathole.

However the C++ side should be able to create instances of the Python-defined subclass as long as it runs in a method, since it has a reference to the actual class. This is what I'm currently doing and it does work, but I'm trying to build my extension type in such a way that it lazily gets initialized as a python object only if it is passed to the python side of things. For this object, 75% of the time, it is created and used in C++ only and I'd like to not pay for the python object creation overhead if I don't have to.

I am putting PyObject_Head at the front of my class, but only initializing it if it is passed to python. I had intended to initialize the python bits with a C++ type, but I guess I could do it with a cached module lookup of the python derived type. Allocation is really tricky too, so this all may just not be worth the hassle. :)

Anyway, if these types of issues are inappropriate for this forum, I'll keep quiet.



More information about the Python-Dev mailing list