python - Order of operation in multiple applications of overloaded __le__ -


in python trying refunction __le__ operator in order chain variables "compared" list

a > b > c should give [a,b,c]

i have tried strange behavior depending on whether or not include brackets between values being compared.

class opque:     def __init__(self,opa,opb):         self.ops = [opa,opb]     def __gt__(self,b): #self > b         #print("gt opque")         if isinstance(b,operation):             self.ops.append(b)             return self         elif isinstance(b,opque):             self.ops.append(b.ops)             return self         else:             raise valueerror class operation:     def __gt__(self,b):#self > b         if isinstance(b,operation):             return opque(self,b)         elif isinstance(b,opque):             b.ops.insert(0,b)             return b         else:             return valueerror  = operation() b = operation() c = operation()  if __name__ == "__main__":     tmp1 =  (a >  b  > c)     print(" no brackets: ",len(tmp1.ops))     tmp2 =  ( (a >  b)  > c)     print(" front brackets: ",len(tmp2.ops))     tmp3 =  (a >  (b  > c))     print(" brackets: ",len(tmp3.ops)) 

surprisingly me gives following result:

 no brackets:  2  front brackets:  3  brackets:  3 

i expect no bracket case same both other ones, missing?

chained comparison operators treated if they're done pairwise and between them. allows write:

if 1 <= x <= 10 

to test if x between 1 , 10. documentation says:

formally, if a, b, c, ..., y, z expressions , op1, op2, ..., opn comparison operators, a op1 b op2 c ... y opn z equivalent a op1 b , b op2 c , ... y opn z, except each expression evaluated @ once.

overloading operator doesn't change special parsing rule.

so when write

tmp1 = (a > b > c) 

it's evaluated as

tmp1 = (a > b , b > c) 

this sets tmp1 result of b > c, [b, c].


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -