On Wed, Jun 23 2021 at 20:48:39 +1000, Steven D'Aprano <steve@pearwood.info> wrote:
I've just thought of a great use-case for extension methods. Hands up who has to write code that runs under multiple versions of Python? *raises my hand* I'm sure I'm not the only one. You probably have written compatibility functions like this: def bit_length(num): try: return num.bit_length() except AttributeError: # fallback implementation goes here ... and then everywhere you want to write `n.bit_length()`, you write `bit_length(n)` instead. Extension methods would let us do this: # compatibility.py @extends(int): def bit_length(self): # fallback implementation goes here ... # mylibrary.py using compatibility num = 42 num.bit_length() Now obviously that isn't going to help with versions too old to support extension methods, but eventually extension methods will be available in the oldest version of Python you care about: # supports Python 3.14 and above Once we reach that point, then backporting new methods to classes becomes a simple matter of using an extension method. No mess, no fuss. As someone who has written a lot of code like that first bit_length compatibility function in my time, I think I've just gone from "Yeah, extension methods seem useful..." to "OMG I WANT THEM TEN YEARS AGO SO I CAN USE THEM RIGHT NOW!!!". Backporting might not be your killer-app for extension methods, but I really do think they might be mine.
--
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/UEERCY5L5MNFJCQQ4BTSCAHKRTOUXGGE/ Code of Conduct: http://python.org/psf/codeofconduct/

Of course that means the the standard library might also introduce something new that will be shadowed by one of your custom methods, and then you'll wish you had just used functions or a wrapper class. If you can import extension methods wholesale, you might even be monkeypatching something without realising it, in which case you'll be lucky if things break in an obvious way.
Honestly, all the use cases in this thread seem to be much better served by using plain old functions.