Python: Self-Modifying Code.

Arman Hossain
2 min readDec 13, 2022

--

Credit: Getty Images/Westend61

“Self-modifying code” refers to a program that can change its code or behaviour at runtime. In Python, this can be done in several ways, such as by changing the attributes of a class on the fly or changing the values of global variables.

Here is an example of self-modifying code in Python:

# Define a global variable that will be used to store the code for a function
code = """
def my_function():
print("This is my function!")
"""

# Define a function that will be used to dynamically create and execute the code for a function
def create_and_execute_function():
# Use the exec() function to dynamically execute the code for a function
exec(code)

# Call the newly created function
my_function()

# Call the create_and_execute_function() function to dynamically create and execute the code for a function
create_and_execute_function() # Output: This is my function!

In this example, we have defined a global variable called code that contains the code for a function called my_function(). We then define a function create_and_execute_function() that uses the exec() function to dynamically execute the code contained in the code variable. This creates a new function called my_function(), which is then called inside the create_and_execute_function() function.

As a result, when we call the create_and_execute_function() function, it creates and executes the code for the my_function() function, which prints a message to the console. This demonstrates how self-modifying code can be used to change the behaviour of a program at runtime.

While self-modifying code can be useful in some cases, it can also be difficult to understand and maintain, making programs more difficult to debug. As such, it should be used with caution and only in situations where it is necessary.

--

--

Arman Hossain
Arman Hossain

Written by Arman Hossain

I love to explore new technologies and leverage them to solve real-life problems. Currently working as the Chief Technology Officer of HelloTask.

No responses yet