Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #103869
| From | Fabien <fabien.maussion@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | urlopen, six, and py2 |
| Date | 2016-03-02 15:05 +0100 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <nb6rvp$cub$1@gioia.aioe.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
urlopen, six, and py2 Fabien <fabien.maussion@gmail.com> - 2016-03-02 15:05 +0100
Re: urlopen, six, and py2 Matt Wheeler <m@funkyhat.org> - 2016-03-02 14:35 +0000
Re: urlopen, six, and py2 Fabien <fabien.maussion@gmail.com> - 2016-03-02 16:36 +0100
Re: urlopen, six, and py2 Chris Angelico <rosuav@gmail.com> - 2016-03-03 03:17 +1100
Re: urlopen, six, and py2 Chris Angelico <rosuav@gmail.com> - 2016-03-03 01:53 +1100
csiph-web