0

Strange question: I want this expression to be True. 1+1==3, although I know it’s not :).

if 1+1==3: 
    print("This is True...")

I know I can do it by creating a class (let’s say a) and overloading its __add__ function, but it requires me to write a(1)+a(1)==3.

Can I do it without writing an additional code (sure I can write code before and after, but the line above will be as is)?

zvi
  • 3,677
  • 2
  • 30
  • 48
  • 1
    You could maybe register a new source codec that wraps literals in a custom class that has the necessary overrides. [This answer](https://stackoverflow.com/questions/37203589/possible-to-make-custom-string-literal-prefixes-in-python) has some pointers for writing custom source codecs. – ddulaney Jan 23 '21 at 22:30
  • Take a look at this [answer](https://stackoverflow.com/a/38832002/11199298). It looks like you can't do that on "normal" Python – Tugay Jan 23 '21 at 22:35
  • @ddulaney great idea I’ll check.. – zvi Jan 23 '21 at 22:39

1 Answers1

1

I managed to do it according to @ddulaney suggestion: create my own codec my_true and write my own decode function.

I have 3 files:

  1. register.py:
import codecs, io, encodings
from encodings import utf_8

def my_true_decode(input, errors="strict"):
    raw = bytes(input).decode("utf-8")
    code = raw.replace('1+1==3','1+1==2')
    return code, len(input)

def search_function(encoding):
    if encoding != "my_true":
        return None
    utf8 = encodings.search_function("utf8")
    return codecs.CodecInfo(
        name="my_true",
        encode=utf8.encode,
        decode=my_true_decode,
    )

codecs.register(search_function)
  1. script.py:
# coding: my_true
if 1+1==3: 
    print("This is True...")
  1. run.py:
import register
import script

Now run python3 run.py

Output is This is True...

zvi
  • 3,677
  • 2
  • 30
  • 48