[Tutor] Using 'requests' + 'with statement' in Python 3.4.1

Danny Yoo dyoo at hashcollision.org
Fri Sep 19 19:50:33 CEST 2014


> Traceback (most recent call last):
>   File "C:\[...]\shark.py", line 98, in <module>
>     main(sys.argv[1])
>   File "C:\[...]\shark.py", line 93, in main
>     fetch_forum()
>   File "C:\[...]\shark.py", line 79, in fetch_forum
>     fetch_user(user_url)
>   File "C:\[...]\shark.py", line 42, in fetch_user
>     backpacktf = check_backpacktf(steamID64)
>   File "C:\[...]\shark.py", line 25, in check_backpacktf
>     with requests.get(''.join([BACKPACKTF, steamID64])) as response:
> AttributeError: __exit__
>
>
> I'm trying to use the 'with statement' to reduce the SLOC and make the code
> prettier. Using 'try-expect-finally' wouldn't be good, as I have more 3 or 4
> functions like this one that call different sites. What's the problem? Can't
> I use requests that way?


I'm not exactly sure.  Let's check the documentation on the 'with'
statement to double check what it expects.

    https://docs.python.org/2/reference/compound_stmts.html#the-with-statement

Reading... ok, so 'with' uses the term "context manager".  From
reading this, I think 'with' only works with things that support the
context manager interface.


Does the return value from requests.get() support context management?
Reading...

    http://docs.python-requests.org/en/latest/api/#requests.Response

... I don't think so.  It does have a 'close()' method, but the with
statement expects an object with both '__enter__' and '__exit__'
methods.


So Python's "with" appears to require a bit more out the thing being
managed than the similar try-with-resources in Java.
(http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)


More information about the Tutor mailing list