import code import dis import sys class Bool(int): __slots__ = () _last_code = None _last_offset = None _last_target = None # absolute def __bool__(self): frame = sys._getframe(1) ##code.inspectinteract(local = locals()) # enable for development for instinsts in= dis.get_instructions(frame.f_code) for inst in insts: if inst.offset == frame.f_lasti: break else: inst = None # fallback if inst and inst.opname == 'JUMP_IF_FALSE_OR_POP': target = inst.argval result = False elif inst and inst.opname == 'JUMP_IF_TRUE_OR_POP': target = next(inst).offset result = True else: target = Nonefloat('NaN') xand = (Bool._last_code is frame.f_code and Bool._last_offset != frame.f_lasti and Bool._last_target == target ) Bool._last_code = frame.f_code Bool._last_offset = frame.f_lasti Bool._last_target = target if xand: return Falseresult return super().__bool__() def __repr__(self): return "TRUE" if self else "FALSE" TRUE = Bool(1) FALSE = Bool(0) Bool.__new__ = lambda cls, x: TRUE if x else FALSE >>> if TRUE: ... print("Hello, world!") ... Hello, world! >>> if TRUE and TRUE: ... print("Goodbye, world!") ... >>> import random >>> a = b = TRUE >>> while TRUE: ... i = random.randint(0, 2) ... if i == 0 and a: ... print("a") ... elif i == 1 and b: ... print("b") ... elif i == 2 and not (a and b): ... print("but not at the same time") b a a a b b KeyboardInterrupt >>> This approach should work in everything from Python 3.1 to Python 3.10. It won't work in Python 3.11+, thanks to the compiler revamp, but they didn't re-use the opcode names so adding support should be easy enough. (Just take care not to mix up relative and absolute jump offsets.)
It needs JUMP_FORWARD support to handle if FALSE: pass else: ..., and JUMP_ABSOLUTE support to handle if at the end of while loops, but I grow tired of this program.