newbie-question: Nested functions and variable scope

Leonardo Boiko leoboiko at linuxbr.com.br
Wed Sep 4 19:03:35 EDT 2002


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) + ">")

    def end_element(name):
        if name == "reply":
            in_reply = 0
        elif not in_reply:
            outfile.write("</" + name.encode(encoding) + ">")
    (...)

As you may have guessed, this gives me an error:
>>> generate_main()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "../xmlgen.py", line 52, in generate_main
    parser.ParseFile(file)
  File "../xmlgen.py", line 22, in start_element
    elif not in_reply:
UnboundLocalError: local variable 'in_reply' referenced before
assignment


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?



More information about the Python-list mailing list