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-le...@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/

Reply via email to