urlopen, six, and py2
Fabien
fabien.maussion at gmail.com
Wed Mar 2 09:05:46 EST 2016
Hi,
it seems that urlopen had no context manager for versions < 3. The
following code therefore will crash on py2 but not on py3.
from six.moves.urllib.request import urlopen
with urlopen('http://www.google.com') as resp:
_ = resp.read()
Error:
AttributeError: addinfourl instance has no attribute '__exit__'
I actually wonder if this is not something that the six library should
take care of upstream, but in the meantime I could simply do what is
suggested on this stackoverflow post:
http://stackoverflow.com/questions/30627937/tracebaclk-attributeerroraddinfourl-instance-has-no-attribute-exit
My question is: why does the python3 version need a "with" block while
the python2 version doesn't? Can I skip the "with" entirely, or should I
rather do the following:
from six.moves.urllib.request import urlopen
try:
with urlopen('http://www.google.com') as resp:
_ = resp.read()
except AttributeError:
# python 2
resp = urlopen('http://www.google.com')
_ = resp.read()
(which is quite ugly).
Thanks!
Fabien
More information about the Python-list
mailing list