Wednesday, March 18, 2015

Unpack a Python object with vars() to see what is inside of it

#!/usr/bin/env python
# Filename:                unpack.py
# Description:             This code will unpack a python object
# Supported Langauge(s):   Python 2.7.x
# Time-stamp:              <2015-03-18 18:41:56 none> 
# -------------------------------------------------------
# I had to figure this out twice I am logging it this time. 
# -------------------------------------------------------

# Suppose we have some object...

class FirstClass:
    def setdata(self, value):
            self.data = value
    def display(self):
            print self.data

# ...and someone instantiated it

x = FirstClass()
y = FirstClass()
x.setdata("King Arthur")
y.setdata(3.14159)

# If someone hands it to me and I want to know what inside 
# it, then printing it just gives me something like 
# <__main__.FirstClass instance at 0x7f794fab7b00>

print x

# Since I have the code to the class I can just use the
# display method. 

x.display()

# But what if I don't know about the dispaly method?
# Is there some way I an unpack any arbitrary object?

vars(x)

# The above returns {'data': 'King Arthur'} . 
# For a more complicated object you can pprint it. 

from pprint import pprint
pprint (vars(x))

Try dir([object]) too.

No comments: