4

I was using python-requests in conjunction with a lambda function (correct me if you call it something else) to GET a url. Given that the url varied according to the value of epoch(), I wanted to print it for debugging.

Lucky for me, print(kiwi.url) works, because kiwi.url exists, but for future reference, how can I find all possible attributes for python-requests, or even other modules, without relying on luck?

import time, requests
epoch = lambda: int(time.time()*1000)
kiwi = s.get('http://www.example.com/api?do=%i' % epoch())
print(kiwi.url) #I found the .url attribute by chance.
           ^
octosquidopus
  • 3,517
  • 8
  • 35
  • 53

2 Answers2

15

Generally speaking you can introspect Python objects with the dir() and vars() functions:

>>> import requests
>>> response = requests.get('http://httpbin.org/get?foo=bar')
>>> dir(response)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getstate__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> 'url' in dir(response)
True
>>> vars(response).keys()
['cookies', '_content', 'headers', 'url', 'status_code', '_content_consumed', 'encoding', 'request', 'connection', 'elapsed', 'raw', 'reason', 'history']

You could also just use the help() function and Python will format the docstrings on a class; response.url doesn't have a docstring but is listed in the attributes section.

For requests specifically, just check out the excellent API documentation. The url attribute is listed as part of the Response object.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Use dir() in the shell:

>>> import requests
>>> req = requests.get('http://www.google.com')
>>> dir(req)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__doc__',
'__format__', '__getattribute__', '__getstate__', '__hash__', '__init__',
'__iter__', '__module__', '__new__', '__nonzero__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed',
'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 
'encoding', 'headers', 'history', 'is_redirect', 'iter_content', 'iter_lines',
'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request',
'status_code', 'text', 'url']
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895