newbie-question: Nested functions and variable scope

Jeremy Hylton jeremy at alum.mit.edu
Thu Sep 5 21:30:13 CEST 2002


leoboiko at linuxbr.com.br (Leonardo Boiko) wrote in message news:<7a7157fd.0209041503.7b9a0f44 at posting.google.com>...
> Hi, I'm a Python newbie. I'm writing a program that uses expat. Some
> code looks like this:
> 
> def generate_main(filename="main.xml", (...)):
>     (...)
>     outfile = open (filename, "w")
>     in_reply = 0 # true if we are inside "reply" element
> 
>     def start_element(name, attrs):
>         if name == "reply":
>             in_reply = 1
>         elif not in_reply:
>             outfile.write("<" + name.encode(encoding) + ">")
   [...]
> If I put "in_reply" outside everything and use "global in_reply"
> inside each nested function, it works, but that's evil! What would be
> a better way of doing it? Do I need to use a class?

You'd be better off using a class.  You can't rebind a name in a
nested scope.  So there is no way to make in_reply a local variable in
generate_main() and rebind it in start_element().

Jeremy



More information about the Python-list mailing list