TAGS :Viewed: 7 - Published at: a few seconds ago

[ 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)

a = 5

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.

Answer 1

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

    def x(self):
        return self.a == self.b


>>> t = Test(a=3, b=5)
>>> t.x
>>> t.a = 5
>>> t.x

Answer 2

Sure, that's called a function! :)

def x(a, b):
    return a == b

Answer 3

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))

Answer 4

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

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)

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).

Answer 5

If you only want the magic to happen when you print x, override __str__.

>>> class X(object):
...     def __str__(self):
...         return str(a == b)
>>> x = X()
>>> print(x)
>>> a = 5
>>> print(x)

Answer 6

make it a simple function:

def f(a,b):
    x= (a==b)
    print x

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