[Python-Dev] Let's get rid of unbound methods

Jp Calderone exarkun at divmod.com
Tue Jan 4 21:15:00 CET 2005


On Tue, 04 Jan 2005 20:02:06 GMT, Jp Calderone <exarkun at divmod.com> wrote:
>On Tue, 4 Jan 2005 10:28:03 -0800, Guido van Rossum <gvanrossum at gmail.com> wrote:
> >In my blog I wrote:
> > 
> > Let's get rid of unbound methods. When class C defines a method f, C.f
> > should just return the function object, not an unbound method that
> > behaves almost, but not quite, the same as that function object. The
> > extra type checking on the first argument that unbound methods are
> > supposed to provide is not useful in practice (I can't remember that
> > it ever caught a bug in my code) and sometimes you have to work around
> > it; it complicates function attribute access; and the overloading of
> > unbound and bound methods on the same object type is confusing. Also,
> > the type checking offered is wrong, because it checks for subclassing
> > rather than for duck typing.
> > 
> 
>   This would make pickling (or any serialization mechanism) of 
> `Class.method' based on name next to impossible.  Right now, with
> the appropriate support, this works:

  It occurs to me that perhaps I was not clear enough here.  

  What I mean is that it is possible to serialize unbound methods 
currently, because they refer to both their own name, the name of 
their class object, and thus indirectly to the module in which they 
are defined.

  If looking up a method on a class object instead returns a function, 
then the class is no longer knowable, and most likely the function will
not have a unique name which can be used to allow a reference to it to 
be serialized.

  In particular, I don't see how one will be able to write something 
equivalent to this:

    import new, copy_reg, types

    def pickleMethod(method):
        return unpickleMethod, (method.im_func.__name__,
                                method.im_self,
                                method.im_class)

    def unpickleMethod(im_name, im_self, im_class):
        unbound = getattr(im_class, im_name)
        if im_self is None:
            return unbound
        return new.instancemethod(unbound.im_func,
                                  im_self,
                                  im_class)

    copy_reg.pickle(types.MethodType, 
                    pickleMethod, 
                    unpickleMethod)

  But perhaps I am just overlooking the obvious.

  Jp


More information about the Python-Dev mailing list