After working with Kotlin for a while I really started to like the idea of extension methods. I delivers a great way to extend the language without having to add features to the language itself.
As a practical example I would like to take a first item from a list
my_list = []
first = my_list[0] # This will obviously throw an error
In this case it would be great to create an extension method like
def list.first_or_none(self):
if len(self):
return self[0]
return None
Or ...
def list.first_or_else(self, fallback_value):
if len(self):
return self[0]
return fallback_value
Then, we could retrieve a value from the list:
from my_list_extensions import first_or_none, first_or_else
first = my_list.first_or_none()
Or ...
first = my_list.first_or_else(0)
Some of the main advantages (not an exhaustive list):
- It also provides a way to add extension methods before adding methods to the standard library, like in PEP 616
- Classes can be extended without using inheritance
- Easier for IDE's to know what methods are available for a type, therefore delivering auto-completion.
- It would also become easier to extend classes from other libraries next to the standard library
- It will be much easier to create methods on a class that can be chained, which leads to less intermediate variables and (in my opinion) better readability. Sometimes these are called fluent builders or fluent interfaces.
my_list.filter(lambda x: x >= 0).map(lambda x: str(x)) instead of [str(x) for x in my_list if x >= 0]. (ok, in hindsight this looks better with the list comprehension, but there are much more complicated examples that would benefit)
A more comprehensive example would be an html builder. Let's say I created a library that builds html from python code, with a nice builder interface:
class Html:
def __init__(self):
self.__items = []
def add_p(self, text):
self.__items.append(text)
return self
def add_h1(self, text):
self.__items.append(text)
return self
def add_div(self, items):
self.__items.append(items)
return self
To add methods (which is very likely in a class like this), I would have to create a subclass, or create a pull request with the author (if the author approves).
In all languages that I know of that have extension methods the most given argument is better code readability.