scoping problem with list comprehension // learning Python
Diez B. Roggisch
deets at nospam.web.de
Thu May 21 04:51:54 EDT 2009
Adrian Dragulescu schrieb:
>
> 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 method.
>
> (Pdb) formatIndex
> '%Y-%m-%d'
> (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)]
> (Pdb)
>
> 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
> using Python30.
I think your problem here is Pdb. You can't always assume that scoping
and assignment works there as desired.
If you do the same in the interpreter instead of Pdb, does it work? It
works for me in Py2.5, don't have a 3.0 handy.
Diez
More information about the Python-list
mailing list