class Some(object):
tokens = [ ... list of strings ... ]
untokenized = [tokens.index(a) for a in [... some other list of strings ...]]
... etc ...
some = Some()
This works fine with Python2.7. However python3 says:
Traceback (most recent call last):
File "./test.py", line 17, in <module>
class Some(object):
File "./test.py", line 42, in Some
untokenized = [tokens.index(a) for a in [... some other list of strings ...]]
File "./test.py", line 42, in <listcomp>
untokenized = [tokens.index(a) for a in [... some other list of strings ...]]
NameError: global name 'tokens' is not defined
Though I can work around the problem, I really would like to know what's difference here between Python2 and Python3. I've read python 2->3 changes documents, but I was not able to identify any description which is related to my problem. Also 2to3
tool does not complain anything in my code.
By the way, though I can't recall the situation now, but I had something similar with python2 only too (I haven't even tried this with 3), I thought this should work (within a class):
def some_method(self):
return {a: eval("self." + a) for a in dir(self) if not a.startswith("_")}
However it causes python2 saying: NameError: name 'self' is not defined
I haven't tried this with python3 yet, but for example this works:
[eval("self." + a) for a in dir(self) if not a.startswith("_")]
If I change the relevant part of the previous example to this one (ok the example itself is a bit stupid, but it shows my problem at least). Now I am very curious, why self
seems not to be defined for this first example but it is for the second? It seems with dicts, I have similar problem that my original question is about, but with list generator expression it works, but not in python3. Hmmm ...
After my python2 -> 3 problem I mentioned this, since all of these seems to be about the problem that something is not defined according to python interpreter (and maybe the second part of my question is unrelated?). I feel quite confused now. Please enlighten me about my mistake (since I am sure I missed something of course).