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

Guido van Rossum guido at python.org
Tue Jan 15 23:19:36 CET 2008


On Jan 15, 2008 2:08 PM, Phillip J. Eby <pje at telecommunity.com> wrote:

At 01:51 PM 1/15/2008 -0800, Guido van Rossum wrote: >On Jan 15, 2008 1:27 PM, "Martin v. Löwis" <martin at v.loewis.de> wrote: > > > Second, a "metaclass" to add a number of methods (or other attributes) > > > to an existing class, using a convenient class notation: > > > > I think this is similar to my "partial" classes: > > > > http://pypi.python.org/pypi/partial > >Indeed it is. I guess my only innovation is realizing that you don't >have to create a real metaclass -- you can set metaclass to a >function that does the magic. I like your feature of refusing >overrides unless flagged with @replace. > >I think that despite the objection that monkeypatching shoudn't be >made too easy, it's worth at looking into a unification of the API, >features, and implementation.

I'm curious: has this affected your thoughts re: overloading existing functions? Note that overloading-in-place would provide the nextmethod idiom for calling the original function. (I'm assuming you still don't like the idea of changing a function's code to do it, just wondering about the non-implementation aspect. :) )

Not really -- I'm still thinking of a class as something with public internal structure while I think of a function as something with private internal structure (except for function attributes settable in its dict).

While I have you, I've come across a need that I don't know how to do with GFs. Suppose I have a GF that implements some recursive function over container types, e.g. serialization or flattening. Now suppose I'd like to create another GF that implements the same algorithm except it does something different for one particular type; as a concrete example, suppose we want to treat tuples atomically when flattening. Is there a way to reuse the work of the first GF? It doesn't work to create a new GF that calls on the first GF for types it doesn't understand; e.g. a list could contain a tuple. Does your GF machinery let me do this in a relatively clean way? (I think of it as "subclassing" a GF, where I think of the GF as a class that has a method for each supported type. If GFs were implemented this way, I could simply subclass it and override the method for tuples.) You might want to change the subject if you care to respond.

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list