[ Can be saved into a variable one condition? ]
It would be possible to store the condition itself in the variable, rather than the immediate return it, when to declare it?
a = 3 b = 5 x = (a == b) print(x) a = 5 print(x)
The return is
However, I expected to get
I'm just having fun with the magic of Python. I know it is possible using a function, but I wonder if it is possible using a variable.
You can get this kind of reactive pattern by using a property:
class Test: def __init__(self, a, b): self.a = a self.b = b @property def x(self): return self.a == self.b
>>> t = Test(a=3, b=5) >>> t.x False >>> t.a = 5 >>> t.x True
Sure, that's called a function! :)
def x(a, b): return a == b
No. You need a function for that.
def test(param_1, param_2): return param_1 == param_2 a = 3 b = 5 print(test(a, b)) a = 3 print(test(a, b))
The condition is always evaluated immediately. If you want to evaluate it on demand, you could make it a function or a lambda expression:
x = lambda: a == b print(x())
Also, you could probably do some black magic and make a class that evaluates the condition when it's printed:
class Condition: def __init__ (self, cond): self.cond = cond def __str__ (self): return str(self.cond()) x = Condition(lambda: a == b) print(x)
This is only for educational purposes though, don't use it in production. Also note that it onl works in print statements - to make it work in
if statements etc you would also have to override
__bool__ (python 3) or
__nonzero__ (python 2).
If you only want the magic to happen when you print x, override
>>> class X(object): ... def __str__(self): ... return str(a == b) ... >>> x = X() >>> print(x) False >>> a = 5 >>> print(x) True
make it a simple function:
def f(a,b): x= (a==b) print x f(3,5) f(5,5)
Additionally, if you are asking if you can store the condition in the variable, You have done that. That is why X holds a value of either true or false depending on the output of the function. if you want to use it with only a variable but not a function you will have to add
print(x) after everytime you update either of the variables