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): https://stackoverflow.com/q/40120596/364696

On Sun, Sep 13, 2020 at 5:24 AM Steven D'Aprano <steve@pearwood.info> 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
result.

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.

*shrug*

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.



--
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/QKAA54IV2WDEEWN354PK3JPSPIAMRGD2/
Code of Conduct: http://python.org/psf/codeofconduct/