by eesmith · 8y ago · 0 comments
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> [a*2 for a in (1,2,3)]
[2, 4, 6]
>>> a
3
In Python 3.x, it is not: >>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> [a*2 for a in (1,2,3)]
[2, 4, 6]
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
It is sometimes useful to know why something failed. The following Python 2 code will not work in Python 3: >>> import math
>>> try:
... values = [math.sqrt(x) for x in (1, 2, -3, 4)]
... except ValueError:
... print("cannot compute sqrt(%r)" % x)
...
cannot compute sqrt(-3)
I have mostly found this feature of Python 2 to be useful on the interactive shell, when trying to diagnose what caused an error in my list comprehension. Eg. >>> with open("tmp.dat") as input_file:
... fields = [line.split()[3] for line in input_file]
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of range
>>> line
'one two three\n'
Oops, there are only 3 columns, not 4. [a := x*2 for x in (1, 2, 3)]
See PEP 572 -- Assignment Expressions: https://www.python.org/dev/peps/pep-0572/I often did:
>>> [d for d in drawings]
>>> [d.<tab> ...]
Because I’m lazy and I want the autocomplete to be there for me. It’s actually the only thing I miss from python 2 and I will admit that a couple of times the sideffects have caught me out in production code so I’m happy with the change.It’s worth noting that the latest python pep is going to give you a way to assign the variables in the outer scope again:
https://www.python.org/dev/peps/pep-0572/#simplifying-list-c...