I am writing a python script in python 3.x in which I need to redefine the print
function. When I do it in my interpreter, it works fine. But when I create a function using the same code, it gives out error.
Here is my code:
list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
old_print = print
def print(s):
global catstr
catstr += s
catstr = ""
for item in list:
s = item
exec(s)
print = old_print
catstr
>> 'Wow!Great!Epic!'
As you can see I have got my desired result: 'Wow!Great!Epic!'
Now I make a function using the same code:
def execute(list):
old_print = print
def print(s):
global catstr
catstr += s
catstr = ""
for item in list:
s = item
exec(s)
print = old_print
return catstr
Now when I run this function using the following code:
list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
execute(list)
I get the following error:
old_print = print
UnboundLocalError: local variable 'print' referenced before assignment
Does anyone know why this is not working within a function?
Any suggestions on how to fix it will be highly appreciated.