Monday, February 15, 2021

Inpsecting Python Objects

It is useful to inspect objects when we run Python interactively. Below is a few commands we can use to inspect Python objects.

  • type
  • dir
  • vars
  • __dict__
Below are a few examples showing how we may use these:

$ python
>>> # This is to show the version of Pyhon I am using.
>>> import sys
>>> print(sys.version)
3.7.9 (default, Aug 19 2020, 17:05:11)
[GCC 9.3.1 20200408 (Red Hat 9.3.1-2)]
>>> 
>>> # create a tempfile.TemporaryDirectory object
>>> import tempfile
>>> d = tempfile.TemporaryDirectory()
>>>
>>> # now inspect the d object
>>> # 1. what is d's data type?
>>> type(d)
<class 'tempfile.TemporaryDirectory'>
>>> # 2. what are d's attributes?
>>> dir(d)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', 
 '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', 
 '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', 
 '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
 '__weakref__', '_cleanup', '_finalizer', 'cleanup', 'name']
>>>
>>> # 3. Return the __dict__ attribute for d
>>> vars(d)
{'name': '/tmp/tmpmjddeo49', '_finalizer': }
>>> 
>>> # this is the same
>>> d.__dict__
{'name': '/tmp/tmpmjddeo49', '_finalizer': }
>>> # so d has an "attribute" called 'name', and it is a string!
>>> type(d.name)
<class 'str'>
>>> d.name
'/tmp/tmpmjddeo49'
>>> # d also has an "attribute" called 'cleanup', and it is a method!
>>> type(d.cleanup)
<class 'method'>
>>> d.cleanup()
>>>