[Python-Dev] the not operator (and the __not__ special method)

Marcelo Matus mmatus@dinha.acms.arizona.edu
Thu, 03 Oct 2002 15:30:34 -0700


Thanks to everybody for your fast and helpful answer.

Clearly I was confused with the similarity between the names  'and': __and__
and  'or' : __or__, and I was thinking they were related, but that is 
not the case.

For now, I can implement my logical classes by using the bitwise 
operators '&,|,~' .

I forgot to say, but what I want to do is something like

    x = vfncs.Identity()                                 # a class instance
    b = x + 2                                                # another 
class  instance
    cond = (sin(x) <= 0.5 ) & ( b > 0.5 )    # another class instance
 
    print  x(0.3)           ==>   0.3
    print  b(0.3)          ==>   2.3
    print  cond(0.3)    ==>   1                    

where x, b and cond are "virtual functions" than can be evaluated  like
lambda functions after they are defined. The difference is that the are 
build from a C++
library, and they can be passed back to the C++ code where
they will be evaluated directly.

Anyway, given that now python has the "rich comparison" engine, where the
operator <=,>,<,>= can return anything you want (and thanks for that, 
because
I can do what I am doing now) and more boolean capabilities are been 
included
(I read that the boolean type is coming soon), I guess it will be also 
good to
have the special methods  for the logical operations 'and', 'or' and 'not',
(something like __land__, __lor__ and __lnot__ to distinguish them from
the bitwise versions __and__ and __or__).

So, if  you overload the proper logical methods, you can write something 
like

  cond = not (sin(x) > 0.5 ) and ( b <= 0.5 )

where 'not' and 'and', like '>' and '<=', wil return anything you want.


Marcelo


Brian Quinlan wrote:

>>shows that python doesn't call the __not__ special method
>>in a 'not' operator statement.
>>    
>>
>
>Python calls the special __nonzero__ method so check the truth value of
>an object.
>
>  
>
>>Another question, I notice than  "a or b" and "a and b" are
>>not equivalent to "a | b" and "a & b", since the last ones call
>>the methods __or__ and __and__ if they are defined, but
>>the "literal forms" never call them.  Is this intentional?, if
>>that is the case, I guess a big and clear note is needed
>>in the documentation.
>>    
>>
>
>"and" and "or" are logical operators, while "|" and "&" are bitwise
>operators. 
>
>  
>
>>>>13 & 14
>>>>        
>>>>
>12
>  
>
>>>>13 and 14
>>>>        
>>>>
>14
>
>  
>
>>And just for symmetry considerations, given that python has the
>>pairs (and, &) and (or, |), does anybody considering to introduce
>>the ! operator, so you can have the equivalent (not, !) too?
>>    
>>
>
>There is a bitwise not operator: ~
>
>  
>
>>>>~2
>>>>        
>>>>
>-3
>
>Cheers,
>Brian
>
>  
>