3

How can I change function names so that Python will read hehe as if, haha as elif and hihi as else. Code right now is something like:

if x == 7 or x == 2:
    print(":)")
elif x == 3:
    print(":(")
else:
    print(":|")

I want my code to be like this:

hehe x == 7 or x == 2:
    print(":)")

haha x == 3:
    print(":(")
hihi:
    print(":|")

I want to change every function's name to make the code completely unreadable. This has no practical usage, I want to make it just for fun. I tried to make a compiler and I've got something similar to basic, but I want to make it in Python without creating a compiler. There should be a solution with dictionaries where the format will be like:

dict = {
"if": "hehe"
"elif": "haha"
"else": "hihi"
}

But I don't know how to make it work in code so I could write code in this "new language" after

Georxy
  • 41
  • 4
  • see if this helps https://stackoverflow.com/questions/20567497/overwrite-built-in-function – Hannon qaoud Sep 25 '22 at 10:38
  • this could help, but to write it to every function will be the same as making a new compiler. I think there could be a solution with dictionaries – Georxy Sep 25 '22 at 10:44
  • 1
    so just to be clear, do you want to be able to write in your new syntax, and run it, or do you want a separate script to encode an existing python code based on your criteria? – Hannon qaoud Sep 25 '22 at 10:52
  • I want to keep Python syntax and create a separate encode script based on my criteria, so I could write code with my "new language" – Georxy Sep 25 '22 at 10:55
  • 2
    `if` is not a function, but a keyword. Changing keywords requires a separate pass over the file and can't be done easily from within the python interpreter: You either need to create a wrapper script or do black magic like abusing the encoding registry. – MegaIng Sep 25 '22 at 11:20
  • this made it a little clearer, I saw some guys did the same thing with JS just using a dictionary and around 50 lines of code. Now I have a clear direction at least – Georxy Sep 25 '22 at 11:45
  • I’m voting to close this question because Stack Overflow's scope is limited to **practical** questions (see the first sentence of the second paragraph of https://stackoverflow.com/help/dont-ask). Making a language identical to Python but giving keywords "funny" names is impractical by nature. – Charles Duffy Sep 25 '22 at 12:24
  • 1
    @CharlesDuffy I would give benefit of the doubt and say that this is a simplified example, not the actual goal. Maybe the actual goal is translated keywords or something similar. – MegaIng Sep 25 '22 at 12:28
  • You can change builtin functions because they are just function attributes of the `builtins` module which is default imported - even if IMHO you should not even try... But `if`, `elsif`, and `else` are not builtin functions but language keywords. So you cannot change them, except with a pre-processor. Maybe you could have a look to [ruby](https://www.ruby-lang.org) language whose syntax allow to call function without any parentheses, which in the end is close to declaring new language keywords... – Serge Ballesta Sep 25 '22 at 13:04

1 Answers1

2

I haven't spent along time on this (it could be improved), this is my first time using the tokenize module, but here's what I came up with.

As I was looking for a python parser I found this module, it basically parses python code and categorizes it, from there you can do what you want with it.

from token import DEDENT, INDENT, NEWLINE
import tokenize
result = ''

names = {
    'if': 'hehe',
    'elif': 'haha',
    'else': 'hihi',
    # Add here all the other names, that you want to change, and don't worry about a name occurring inside a string it will not be changed
}
# open the script you want to encrypt in a tokenize file object
with tokenize.open('z.py') as f:
    # create a new tokenize object and feed it the lines
    tokens = tokenize.generate_tokens(f.readline)
    # for every token in all the tokens in the file:
    for token in tokens:
        if names.get(token[1]): # token[1] is the string of the token i.e 'if', 'for', '\n', 'or' etc
            result += names.get(token[1]) + ' '
        elif token.type == NEWLINE or token[1] == INDENT or token.type == DEDENT:
            result += token[1]
            print(result)
        else:
            result += token[1] + ' '


with open('z.py', 'w') as f:
    f.write(result)

update

the previous code, only encodes, with some minor alterations, you can reuse the same code to decode and encode the script:

from token import DEDENT, INDENT, NEWLINE
import tokenize

encode_name = {
    'if': 'hehe',
    'elif': 'haha',
    'else': 'hihi',
}

def code(name, encode=True):
    if encode:
        names = name
    else:
        # flip the dict, keys become values and vice versa
        names = {v: k for k, v in name.items()}
    
    result = ''
    with tokenize.open('z.py') as f:
        tokens = tokenize.generate_tokens(f.readline)
        for token in tokens:
            if names.get(token[1]):
                result += names.get(token[1]) + ' '
            elif token.type == NEWLINE or token[1] == INDENT or token.type == DEDENT:
                result += token[1]
            else:
                result += token[1] + ' '

    with open('z.py', 'w') as f:
        f.write(result)


code(encode_name, encode = False)

check out the official docs for more information i am no expert my self but don't hesitate to ask anything here.

very happy to help good luck, happy coding

Hannon qaoud
  • 785
  • 2
  • 21
  • Thank you! But how could I write code in this "language" and make it work like normal code? Could you please help me with the decoding process as well? :D but so I could import module with this and start writing in this language – Georxy Sep 25 '22 at 12:08
  • updated to decode and encode, make sure to mark the most correct answer :) . – Hannon qaoud Sep 25 '22 at 12:21
  • 1
    now we are back talking a bout completely changing python behavior, which is not my domain and i dont know if its even possible, from a module, your talking about creating a whole new personalized copy of python, which is more than me and you and this whole website, good luck on your mission – Hannon qaoud Sep 25 '22 at 12:30