python - Can be saved into a variable one condition? -


it possible store condition in variable, rather immediate return it, when declare it?

example:

a = 3 b = 5  x = (a == b) print(x)  = 5 print(x) 

the return is

false false 

however, expected get

false true 

i'm having fun magic of python. know possible using function, wonder if possible using variable.

the condition evaluated immediately. if want evaluate on demand, make function or lambda expression:

x = lambda: == b print(x()) 

also, black magic , make class evaluates condition when it's printed:

class condition:   def __init__ (self, cond):     self.cond = cond   def __str__ (self):     return str(self.cond())  x = condition(lambda: == b) print(x) 

this educational purposes though, don't use in production. note onl works in print statements - make work in if statements etc have override __bool__ (python 3) or __nonzero__ (python 2).


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -