The immediate use case I can think of this for is to make it possible to just do:

__len__ = instancemethod(operator.attrgetter('_length'))
__hash__ = instancemethod(operator.attrgetter('_cached_hash'))

and stuff like that. Mostly just a minor performance optimization to avoid the overhead of Python level function calls (and in the case of stuff like __hash__, reduce the probability of the GIL releasing during a dict/set operation, though you'd still need some way to move __eq__ to the C layer to allow stuff like setdefault to be truly atomic).

This was possible in Python 2 with types.MethodType (since it could make unbound methods of a class for you; unbound methods no longer exist). Now the solution is... considerably uglier (requires ctypes):

On Sun, Sep 13, 2020 at 5:24 AM Steven D'Aprano <> wrote:
On Sun, Sep 13, 2020 at 12:32:54AM -0400, Random832 wrote:

> This isn't what I was suggesting - I meant something like this:
> class instancemethod:
>     def __init__(self, wrapped):
>         self.wrapped = wrapped
>     def __get__(self, obj, objtype):
>         if obj is None: return self.wrapped
>         else: return MethodType(self.wrapped, obj)
> this wouldn't be useful for functions, but would give other callables
> the same functionality as functions, automatically creating the bound
> method object, e.g.:
> class D:
>     def __init__(self, obj, *args): ...
> class C:
>     foo = instancemethod(D)

You want a method which does absolutely nothing at all but delegate to a
class constructor or callable object (but not a function), with no
docstring and no pre-processing of arguments or post-processing of the

Seems like an awfully small niche for this to be in the stdlib.

But having said that, I might have a use for that too. Except... I would
need a docstring. And pre- and post-processing. Hmmm.


Seems to me that this might be useful in theory, but in practice we
might never use it, preferring this instead:

    class C:
        def foo(self, *args):
            """Doc string."""
            return D(self, *args)

with appropriate pre- and post-processing as needed.

Interesting suggestion though, I may have to play around with it.

Python-ideas mailing list --
To unsubscribe send an email to
Message archived at
Code of Conduct: