Emile van Sebille a écrit :
On 6/17/2009 3:54 PM ssc said...
Wow! Didn't expect that kind of instant support. Thank you very much,
I'll give both zip and enumerate a try.
The code I've shown is actually copied pretty straight from a Django
form class, but I didn't want to mention that as not to dilute the
conversation. Don't think it matters, anyway. This is the relevant
excerpt:
from django.forms import Form
class SignupForm(Form):
titles = ['Dr', 'Miss', 'Mr', 'Mrs', 'Ms',]
title_choices = [(0, '')] + list((titles.index(t)+1, t) for t in
titles)
Now that I look at it again, it seems odd to me to not have the code
e.g. in __init__(...), but just 'class-global'.
And as class is an executable statement, I imagine titles exists in a
namespace that hasn't yet been completely defined.
Still, that does not seem a reason for titles not to be not defined,
as I do define it just in the line above.
Well, again, titles will exists in the SignupForm namespace once it
exists, which it doesn't yet when you get to title_choices and want to
access it.
The namespace itself is as defined at any point of the class statement's
body as the local namespace of a function at any given point of the
function's body. Else decorators (or their alternate pre '@'
syntactic-sugar version) wouldn't work.
FWIW, the following code works JustFine(tm):
br...@bruno:~$ python
Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
[GCC 4.3.2] on linux2
>>> class Foo(object):
... bar = ['a', 'b', 'c']
... baaz = list(enumerate(bar))
as well as this one:
>>> class Foo(object):
... bar = ['a', 'b', 'c']
... baaz = [(bar.index(t)+1, t) for t in bar]
and this one:
>>> class Foo(object):
... bar = ['a', 'b', 'c']
... baaz = list((b, b) for b in bar)
but it indeed looks like using bar.index *in a generator expression*
fails (at least in 2.5.2) :
>>> class Foo(object):
... bar = ['a', 'b', 'c']
... baaz = list((bar.index(b), b) for b in bar)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in Foo
File "<stdin>", line 3, in <genexpr>
NameError: global name 'bar' is not defined
Looks like a bug to me :-/
--
http://mail.python.org/mailman/listinfo/python-list