Saturday, May 18, 2013

Python's inspect module is powerful

27.13. inspect — Inspect live objects — Python v2.7.5 documentation

The inspect module comes as part of the standard library of Python. It allows you to inspect live objects at run time by using its methods.

Here is an example:

import inspect
class Bar( object):
    def foo( self ):
        print "in Bar.foo 4"
        self .a = 1
        self .di = { 'b' : 2, 'c' : 3 }
        self .li = [  4, 5, 6 ]

bar = Bar()
bar.foo()
for member in inspect.getmembers(bar):
    print member

Running the above code gives this as (partial) output:

in Bar.foo 4

('__dict__', {'a': 1, 'li': [4, 5, 6], 'di': {'c': 3, 'b': 2}})
('__doc__', None)
('a', 1)
('di', {'c': 3, 'b': 2})
('foo', bound method Bar.foo of __main__.Bar object at 0x4035bfac)
('li', [4, 5, 6])

This shows both the bound methods and the member variables of the instance bar.

The inspect module can do a lot of other things too. Check the docs for it, linked at the top of this post.

You can also modify and run the above code snippet at this codepad.org URL:

http://codepad.org/dMLmkhQ6

It may not last there for too long, though, since they probably delete pastes to make room for new ones.

- Vasudev Ram
dancingbison.com

No comments: