scoping problem with list comprehension // learning Python
adrian_d at eskimo.com
Wed May 20 23:53:39 CEST 2009
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) [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.
If I run it as a stand-alone, it works:
index = ['2007-01-01', '2007-01-02', '2007-01-03']
formatIndex = '%Y-%m-%d'
print([datetime.strptime(i, formatIndex) for i in index])
Any suggestions much appreciated. I'm sure it's something trivial. I'm
More information about the Python-list