3
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?

rdas
  • 20,604
  • 6
  • 33
  • 46
Dan
  • 144
  • 1
  • 8
  • why you need this? – ᴀʀᴍᴀɴ May 05 '19 at 09:20
  • 4
    I'm wondering if this might be possible with threads. That's a multi-bytecode condition, if you get really lucky (or unlucky) all 3 conditions might evaluate to `True` if some thread is mutating `a` in the background. – rdas May 05 '19 at 09:25
  • 1
    I guess there is chance in multi-thread as not atomic. – atline May 05 '19 at 09:28
  • 2
    If you're accessing shared state (i.e. variables) without proper locking, then the results will chaotic, however, (C)Python only releases the GIL every 100 byte codes, so this if statement would never evaluate to True because of a background thread. – thebjorn May 05 '19 at 09:40

3 Answers3

7

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
thebjorn
  • 26,297
  • 11
  • 96
  • 138
2

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
knh190
  • 2,744
  • 1
  • 16
  • 30
0

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')
atline
  • 28,355
  • 16
  • 77
  • 113