[Python-ideas] Pseudo methods

Paul Moore p.f.moore at gmail.com
Fri Aug 4 04:16:01 EDT 2017


On 4 August 2017 at 08:39, Paul Laos <paul_laos at outlook.com> wrote:
> Hi folks
> I was thinking about how sometimes, a function sometimes acts on classes,
> and behaves very much like a method. Adding new methods to classes existing
> classes is currently somewhat difficult, and having pseudo methods would make that
> easier.

Adding new methods to classes is deliberately (somewhat) difficult, as
it makes it harder to locate the definition of a method. If you need
to see the code for a method, you'd expect to look in the class
definition. Making it common for people to put method definitions
outside the class definition harms supportability by breaking that
assumption.

> Code example: (The syntax can most likely be improved upon)
>     def has_vowels(self: str):
>         for vowel in ["a", "e,", "i", "o", "u"]:
>             if vowel in self: return True
>
> This allows one to wring `string.has_vowels()` instead of
> `has_vowels(string)`,
> which would make it easier to read,

That's very much a subjective view. Personally, I don't see
"string.has_vowels()" as being any easier to read - except in the
sense that it tells me that I can find the definition of has_vowels in
the class definition of str (and I can find its documentation in the
documentation of the str type). And your proposal removes this
advantage!

> and would make it easier to add
> functionality to existing classes, without having to extend them. This would
> be useful for builtins or imported libraries, so one can fill in "missing"
> methods.

This is a common technique in other languages like Ruby, but is
considered specialised and somewhat of an advanced technique
(monkeypatching) in Python. As you say yourself, the syntax will make
it *easier* to do this - it's already possible, so the change doesn't
add any new capabilities. Adding new syntax to the language typically
needs a much stronger justification (either in terms of enabling
fundamentally new techniques, or providing a significantly more
natural spelling of something that's widely used and acknowledged as a
common programming idiom).

Sorry, but I'm -1 on this change. It doesn't let people do anything
they can't do now, on the contrary it makes it simpler to use a
technique which has readability and supportability problems, which as
a result will mean that people will be inclined to use the approach
without properly considering the consequences.

Paul


More information about the Python-ideas mailing list