A Simple Way to Find Python Object Variables and Functions – Python Tutorial

By | July 16, 2019

In python application, we often use other library to get a python object. However, we often do not know what functions and variables in this object. In this tutorial, we will introduce you a simple way to find python object attributes and functions.

python dir function

For example, if you have use urllib.request.urlopen() to get an http.client.HTTPResponse object. Then how to process this HTTPResponse object next, which means you should know what variables and function in this response object.

response = urllib.request.urlopen(req)

To find the variables and functions in a python object, we can use dir() function.

Find variables and functions in a python object

print(type(response))
print(dir(response))

The result is:

<class 'http.client.HTTPResponse'>
['__abstractmethods__', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_abc_cache', '_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_check_close', '_close_conn', '_get_chunk_left', '_method', '_peek_chunked', '_read1_chunked', '_read_and_discard_trailer', '_read_next_chunk_size', '_read_status', '_readall_chunked', '_readinto_chunked', '_safe_read', '_safe_readinto', 'begin', 'chunk_left', 'chunked', 'close', 'closed', 'code', 'debuglevel', 'detach', 'fileno', 'flush', 'fp', 'getcode', 'getheader', 'getheaders', 'geturl', 'headers', 'info', 'isatty', 'isclosed', 'length', 'msg', 'peek', 'read', 'read1', 'readable', 'readinto', 'readinto1', 'readline', 'readlines', 'reason', 'seek', 'seekable', 'status', 'tell', 'truncate', 'url', 'version', 'will_close', 'writable', 'write', 'writelines']

From the result, we can know:

  1. response is an http.client.HTTPResponse object
  2. it contains status, url, version etc al variables and read(), readline(), write() et al. functions.