Redefining print function not working within a function
<p>I am writing a python script in python 3.x in which I need to redefine the <code>print</code> 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.</p>

<p>Here is my code:</p>

<pre><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
&gt;&gt; 'Wow!Great!Epic!'
</code></pre>

<p>As you can see I have got my desired result: <code>'Wow!Great!Epic!'</code></p>

<p>Now I make a function using the same code:</p>

<pre><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
</code></pre>

<p>Now when I run this function using the following code:</p>

<pre><code>list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]

execute(list)
</code></pre>

<p>I get the following error:</p>

<pre><code>old_print = print 
UnboundLocalError: local variable 'print' referenced before assignment
</code></pre>

<p>Does anyone know why this is not working within a function?<br>
Any suggestions on how to fix it will be highly appreciated.</p>

<p>The interpreter doesn't recognize <strong>print</strong> as the built-in function unless you specifically tell it so.  Instead of declaring it global, just remove it (thanks to Padraic Cunningham): the local <strong>print</strong> will take on your desired definition, and the global is never affected.</p>

<p>You also have a forward-reference problem with <strong>catstr</strong>.  The below code elicits the desired output.</p>

<pre><code>catstr = ""
def execute(list):

    def print(s):
        global catstr
        catstr += s

    for item in list: 
        s = item
        exec(s)
    print = old_print
    return catstr

list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]

print (execute(list))
</code></pre>

python function printing exec