Python dot-equals (syntax proposal)

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat May 1 20:58:10 EDT 2010


On Sun, 02 May 2010 05:08:53 +1000, Lie Ryan wrote:

> On 05/01/10 11:16, Steven D'Aprano wrote:
>> On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote:
>> 
>> In practice though, I think that's a difference that makes no
>> difference. It walks like an operator, it swims like an operator, and
>> it quacks like an operator.
>> 
>> 
> Nope it's not. A full-time operator in python have a reflected version
> (e.g. __radd__), which dot does not have. 

What are the reflected versions of __eq__ and __ne__ (binary == and != 
operators)?

And __neg__, __pos__ and __inv__ (for the unary - + and ~ operators)?

And the three-argument form of __pow__ for power(1, 2, x)?



> And Python's object system
> makes it that the argument to __getattr__ is always a string even though
> there might be a valid variable that corresponds to it:

That is nothing to do with the object system, it is related to the 
semantics of Python syntax. a.b doesn't mean "apply the binary dot 
operator to arguments a and b". It is syntactic sugar for "look for an 
attribute named 'b' on object a". As such, the operands that __getattr__ 
receives are the object a and the *name* b (implemented as a string).

Also, the implementation of attribute lookup is quite complex, with all 
sorts of special cases and optimizations.


> a = MyClass()
> b = MyClass()
> print a . b
> 
> I've often wanted to figure out a way to (ab)use python's dot operator
> for function composition (i.e. f.g(x) ==> f(g(x)) ). There's no way to
> do it, not without being way too hackish.

That's a good example of where the difference does make a difference.



-- 
Steven



More information about the Python-list mailing list