Global confusion

David Ascher da at ski.org
Tue Sep 28 17:41:34 EDT 1999


On Tue, 28 Sep 1999, Gaetan Corneau wrote:

> # Function to add a paragraph
> def AddParagraph(style, text):
>     Srv.ActiveDocument.Paragraphs[nbPar].Range.InsertParagraphAfter()
>     Srv.ActiveDocument.Paragraphs[nbPar].Range.Style =
> Srv.ActiveDocument.Styles(style)
>     Srv.ActiveDocument.Paragraphs[nbPar].Range.InsertAfter(text)
>     nbPar = nbPar + 1

> NameError: nbPar
> 
> I looked in my "Learning Python" book and told my friend to insert  "global
> nbPar" as the first line of the "AddParagraph" function.
> It works, but I don't understand why he has to do that...
> 
> Anybody who can exlain?

The problem is that because nbPar is *assigned to* in the function body,
Python tags all references to 'nbPar' within that function as references
to a local variable (which fails, because nbPar doesn't have a 'local'
value inside the function when the nbPar + 1 is evaluated. The general
rule about Local-Global-Builtin namespaces applies to variables which are
not otherwise tagged.  The global declaration is one such (explicit)
tagging, which is needed to counter the effect of the (implicit) tagging
done by Python at compilation time.

Side note 1: in the next version of Python, a different error message
             UnboundLocalError (or such) will be raised instead.

Side note 2: JPython does something else altogether.  

Side note 3: Since you do want to modify the global variable, adding the
             global declaration is the right thing to do.

Hope this helps.

--david ascher







More information about the Python-list mailing list