Search code examples
pythonobjectintrospectiontweepy

How to "see" the structure of an object in python


I am wokring in python 2.7. I have been experimenting with the tweepy package. There is an object called the tweepy.models.status object, whose function is defined here: https://github.com/tweepy/tweepy/blob/master/tweepy/models.py.

I have a function that looks like this:

    def on_status(self, status):
        try:
            print status
            return True
        except Exception, e:
            print >> sys.stderr, 'Encountered Exception:', e
            pass

The object I am referring to is the one returned from the on_status function, called status. When the print status line executes i get this printed on the screen;

tweepy.models.Status object at 0x85d32ec>

My question is actually pretty generic. I want to know how to visually print out the contents of this status object? I want to know what information is available inside this object.

I tried the for i, v in status : approach, but it says this objects is not iterable. Also not all of the object attributes are described in the function definition.

Thanks a lot!


Solution

  • You could iterate over status.__dict__.items():

    for k,v in status.__dict__.items():  #same thing as `vars(status)`
        print k,v
    

    The above approach won't work if the class uses __slots__ and doesn't have a slot for __dict__. Classes with __slots__ are quite rare though, so it's unlikely to be a problem.

    Alternatively, you could use the dir builtin with getattr:

    for attr in dir(status):
        print attr, getattr(status,attr)
    

    This does work for classes with __slots__, but has some limitations if a custom __getattr__ is defined (see link, and __dict__ would suffer in the same way).

    Finally, if you want really fine control over what you see (e.g. if you only want methods), you can check out some of the goodies in the inspect module.