On 2021-06-20 7:48 p.m., Steven D'Aprano wrote:
The technique you are calling "extension methods" is known as "monkey-patching" in Python and Ruby.
With respect to a fine language, Kotlin, it doesn't have the user-base of either Python or Ruby. Python does not allow monkey-patching builtin classes, but Ruby does:
A cautionary tale. So what does Kotlin do to prevent that sort of thing?
Can you use a regular function that takes a list as argument, instead of monkey-patching the list class to add a method?
The beauty of a function is that every module is independent, so they can add their own list extensions (as functions) without stomping over each other. Whereas if they add them directly on to the list class itself, they can clash.
The trick to extension methods is that they're only available when you explicitly use them.
In other words, a module/package can't force them on you.
The problem with "monkey-patching" is that it *does* get forced on you.
With the way Python works, your only option to implement extension methods is to monkey-patch __getattr__. An alternative would be to have a module-level __getattr__, which by default resolves to the object's own attributes, but can be replaced by the module to provide proper (module-local) extension methods functionality. Thus, any module-local extension methods would also take priority over subclasses' attributes, without conflicting with them.
(It would also slow everything down af, but that's beside the point.)