scoping problem with list comprehension // learning Python
benjamin at python.org
Thu May 21 02:52:57 CEST 2009
Adrian Dragulescu <adrian_d <at> eskimo.com> writes:
> I just started to learn python (first posting to the list).
> I have a list of dates as strings that I want to convert to a
> list of datetime objects. Here is my debugging session from inside a
> (Pdb) formatIndex
> (Pdb) [datetime.strptime(i, formatIndex) for i in self.index[0:3]]
> *** NameError: global name 'formatIndex' is not defined
> (Pdb) [datetime.strptime(i, '%Y-%m-%d') for i in self.index[0:3]]
> [datetime.datetime(2007, 1, 3, 0, 0), datetime.datetime(2007, 1, 4, 0, 0),
> datetime.datetime(2007, 1, 5, 0, 0)]
> How come I get an error that formatIndex is not defined? I just show that
> it has value '%Y-%m-%d', in the same method scope. Not sure why it says
> "global name", as I am in a method.
List comprehensions are implemented as nested functions. To be able to use
variables from the outer scope, the compiler has to "see" the list comp in the
context of the whole function. Thus, when you generate one dynamically (through
user input), the compiler doesn't correctly make a closure.
More information about the Python-list