Python: function to alter a global variable that is also parameter
<pre><code>def fxn(L):
    """ 
    """
    global L = 2

L = 1
fxn(L)
print(L)
</code></pre>

<p>I have a function like the one above. Assume I need the function to alter the global variable from within the function so that when I print L after calling fxn(L). I end up with the 2 rather than 1. </p>

<p>Is there any way to do this? I cant use global L in the function because L is also a parameter.</p>

<p>You should not use the same variable as global variable and the functional argument to the function using that global variable. </p>

<p>But since you have asked, you can do it using the <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow"><code>globals()</code></a> and <a href="https://docs.python.org/2/library/functions.html#locals" rel="nofollow"><code>locals()</code></a>. Below is the sample code:</p>

<pre><code>&gt;&gt;&gt; x = 5
&gt;&gt;&gt; def var_test(x):
...     print('GLOBAL x: ', globals()['x'])
...     print('LOCAL x: ', locals()['x'])
...     globals()['x'] = 111
...     print('GLOBAL x: ', globals()['x'])
...     print('LOCAL x: ', locals()['x'])
...
&gt;&gt;&gt; var_test(20)
GLOBAL x:  5
LOCAL x:  20
GLOBAL x:  111
LOCAL x:  20
</code></pre>

python function global