scoping problem with list comprehension // learning Python

A

Adrian Dragulescu

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.

Adrian
 
D

Diez B. Roggisch

Adrian said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top