__set_name__ equivalent for instance

Dom Grigonis dom.grigonis at gmail.com
Thu Nov 16 14:11:18 EST 2023



> On 16 Nov 2023, at 21:00, Dieter Maurer <dieter at handshake.de> wrote:
> 
> Dom Grigonis wrote at 2023-11-16 20:12 +0200:
>> What I am interested in is a callback.
>> Preferably just after methods get bound. So in `object.__new__`.
> 
>> I have done it via metaclass, but it is not ideal as there would be too much overhead.
>> 
>> I think what I am looking for is custom method binding.
> 
> Methods are not bound during instance creation, they are bound during
> access.

Good to know. What is the criteria for binding then? Does it check if its type is `vanilla` function? If yes, is there any way to simulate it for arbitrary object?

I have tried inheriting from function type, but not allowed.

> You can use descriptors to implement "custom method binding".
> 
> Descriptors are defined on the class (and do not behave as
> descriptors when defined on instances).
> Thus, you would need a metaclass or `__inist_subclass__` is you
> want your "custom method binding" globally.

Yes, I have tried that. This works well. But maybe will be useful for another case.

Currently, the focus is decorators that can be used on arbitrary methods. Needing to inherit and add metaclasses whenever I want to decorate is not an option.

I think I will continue with descriptor approach and am slowly finding route to get where I need to, but still exploring options.

Regards,
DG


More information about the Python-list mailing list