Overwritting print function in Python

Overwritting print function in Python

Did you knew that you can easily overwrite print function using FunctType? Use code below to see how it works.

import random
def random_str():
    return random.choice([
        'first', 'second', 'third'
    ])

def alt_print(s):
    output = []
    for ch in s:
        c = ord(ch)
        if c in range(ord('a'), ord('z')+1):
            c += 119945
        elif ord('A') <= c <= ord('Z'):
            c += 119951
        output.append(chr(c))
        output.append(' ')
    print(''.join(output))


def firstFunction(s="test"):
    print(s)

import types
myFirstFunction = types.FunctionType(
    firstFunction.__code__,
    {
        "print": alt_print
    },
    name="myFirstFunction",
    argdefs=("Function",) # <= there is "," in the end - IT HAS TO BE THERE
)

myFirstFunction()