newbie-question: Nested functions and variable scope

Gerhard Häring gerhard.haering at opus-gmbh.net
Thu Sep 5 09:17:41 CEST 2002


Leonardo Boiko wrote:
> Hi, I'm a Python newbie.

... and using something older than Python 2.2, it seems.

> 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
> [...]

> UnboundLocalError: local variable 'in_reply' referenced before
> assignment

- Python < 2.1 doesn't have nested scopes; you'd have to play tricks with
  lambda IIRC; but then, I consider Python < 2.1 obsolete
- Python 2.1 has nested scopes, if the first import statement in a module
  is "from future import nested_scopes".
- Python 2.2 and later always use nested scopes

> 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?

Just put a "from __future__ import nested_scopes" at the top of your module
and it should just work.

-- Gerhard



More information about the Python-list mailing list