Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When Python parses the body of a function definition and encounters an assignment such as </p> <pre><code>feed = ... </code></pre> <p>Python interprets <code>feed</code> as a local variable by default. If you do not wish for it to be a local variable, you must put </p> <pre><code>global feed </code></pre> <p>in the function definition. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes <code>feed</code> a global variable <em>everywhere</em> in the function.</p> <p>Without the global statement, since <code>feed</code> is taken to be a local variable, when Python executes</p> <pre><code>feed = feed + 1, </code></pre> <p>Python evaluates the right-hand side first and tries to look up the value of feed. The first time through it finds <code>feed</code> is undefined. Hence the error.</p> <p>The shortest way to patch up the code is to add <code>global feed</code> to the beginning of <code>onLoadFinished</code>. The nicer way is to use a class:</p> <pre><code>class Page(object): def __init__(self): self.feed = 0 def onLoadFinished(self, result): ... self.feed += 1 </code></pre> <p>The problem with having functions which mutate global variables is that it makes it harder to grok your code. Functions are no longer isolated units. Their interaction extends to everything that affects or is affected by the global variable. Thus it makes larger programs harder to understand. </p> <p>By avoiding mutating globals, in the long run your code will be easier to understand, test and maintain.</p>
 

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