Dan
Dan

Reputation: 144

How is this if statement possible?

if (a == 1 and a == 2 and a == 3):

Is there a possible way for the if statement above to be true in Python for the variable 'a' ? If so, how can it be?

Upvotes: 3

Views: 104

Answers (3)

atline
atline

Reputation: 31584

I use generator/coroutine to simulate the behavior.

So if in user space level, there is a chance to change value of a with something like coroutine, then I think if use os level thread, there is sure some chance os will yield cpu time during a == 1 and a == 2 and a == 3 as it's not atomic.

def fun():
    yield 1
    yield 2
    yield 3

f = fun()
a = next(f) # simulate os level thread dispatcher
if a == 1:
    a = next(f) # simulate os level thread dispatcher
    if a == 2:
        a = next(f) # simulate os level thread dispatcher
        if a == 3:
            print('come here')

Upvotes: 0

knh190
knh190

Reputation: 2882

Everything in Python is an object and the == operator is actually equivalent to the magic method __eq__.

Calling 1 == 2 is equivalent to (1).__eq__(2), and your own == for customized classes can be implemented as:

class Number(object):
    def __init__(self, x):
        self.x = x
    def __eq__(self, y):
        return self.x == y

a = Number(1)
a == 2 # False

Upvotes: 2

thebjorn
thebjorn

Reputation: 27311

It's possible if you define a degenerate __eq__:

class A:
    def __eq__(self, other):
        return True

a = A()
if a == 1 and a == 2 and a == 3:
    print('equal')
else:
    print('not equal')

which prints:

equal

Upvotes: 7

Related Questions