Note that there are some explanatory texts on larger screens.

plurals
  1. POpython dictionary passed as an input to a function acts like a global in that function rather than a local
    primarykey
    data
    text
    <p>I am very confused by the behaviour below. Cases 1, 3, and 4 perform as I would expect, but case 2 does not. Why does case 2 allow the function to change the value of the dictionary entry globally, even though the dictionary is never returned by the function? A main reason I am using functions is to isolate everything in the function from the rest of the code, but this does not seem to be possible if I choose to use the same variable names inside of the function. I was under the understanding that anything explicitly defined in a function is local to that function, but this does not seem to be the case if the dictionary is <strong>defined and passed as an input to the function</strong>.</p> <pre><code>Python 2.7.2+ (default, Oct 4 2011, 20:06:09) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. </code></pre> <p>=============Case 1===============</p> <pre><code>&gt;&gt;&gt; def testfun1(a): ... a=2 ... &gt;&gt;&gt; a=0 &gt;&gt;&gt; testfun1(a) &gt;&gt;&gt; a 0 </code></pre> <p>=============Case 2===============</p> <pre><code>&gt;&gt;&gt; def testfun2(b): ... b['test']=2 ... &gt;&gt;&gt; b={} &gt;&gt;&gt; testfun2(b) &gt;&gt;&gt; b {'test': 2} </code></pre> <p>=============Case 3===============</p> <pre><code>&gt;&gt;&gt; def testfun3(): ... c=2 ... &gt;&gt;&gt; c=0 &gt;&gt;&gt; testfun3() &gt;&gt;&gt; c 0 </code></pre> <p>=============Case 4=============== (explained by this question: <a href="https://stackoverflow.com/questions/14323817/global-dictionaries-dont-need-keyword-global-to-modify-them">Global dictionaries don&#39;t need keyword global to modify them?</a>)</p> <pre><code>&gt;&gt;&gt; def testfun4(): ... d['test']=10 ... &gt;&gt;&gt; d={} &gt;&gt;&gt; testfun4() &gt;&gt;&gt; d {'test': 10} </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload