Uniform Function Call Syntax (UFCS)

Marko Rauhamaa marko at pacujo.net
Mon Jun 9 02:25:33 EDT 2014


Steven D'Aprano <steve+comp.lang.python at pearwood.info>:

> On Sun, 08 Jun 2014 18:56:47 +0300, Marko Rauhamaa wrote:
>> In fact, what's the point of having the duality?
>>    x < y <==> x.__lt__(y)
>
> [...]
>
> Consider x + y. What happens?
>
> #1 First, Python checks whether y is an instance of a *subclass* of x. If 
> so, y gets priority, otherwise x gets priority.
>
> #2 If y gets priority, y.__radd__(x) is called, if it exists. If it 
> returns something other than NotImplemented, we are done.
>
> #3 However if y.__radd__ doesn't exist, or it returns NotImplemented, 
> then Python continues as if x had priority.
>
> #3 If x has priority, then x.__add__(y) is called, if it exists. If it 
> returns something other than NotImplemented, we are done. 
>
> #4 However if it doesn't exist, or it returns NotImplemented, then 
> y.__radd__(x) is called, provided it wasn't already tried in step #2.
>
> #5 Finally, if neither object has __add__ or __radd__, or both return 
> NotImplemented, then Python raises TypeError.

In a word, Python has predefined a handful of *generic
functions/methods*, which are general and standard in GOOPS (Guile's
object system):

   (define-method (+ (x <string>) (y <string)) ...)
   (define-method (+ (x <matrix>) (y <matrix>)) ...)
   (define-method (+ (f <fish>) (b <bicycle>)) ...)
   (define-method (+ (a <foo>) (b <bar>) (c <baz>)) ...)

   <URL: http://www.gnu.org/software/guile/manual/html_node/
   Methods-and-Generic-Functions.html>


Marko



More information about the Python-list mailing list