Friday, May 31, 2013

see(), an alternative to Python's dir()

see()

The see module for Python works as a somewhat more programmer-friendly version of Python's dir() built-in.

One example of how see() is useful: it does not show all the standard / built-in attributes (including many with double underscores in the name) that are present in the global namespace, when all you do is this:

dir([])

, i.e. when you call dir() on a list. So it has less  cluttered output.

dir() shows all those attributes, e.g.:

    ['__add__', '__class__', '__contains__',
'__delattr__', '__delitem__',   ...

Another example of using see():

    >>> foo = 'bar'
    >>> see(foo, '.is*')
        .isalnum()    .isalpha()    .isdigit
()    .islower()    .isspace()
        .istitle()    .isupper()

from which you can see (pun intended:) that it can also show all (and only) the attributes of foo (a string) that start with the letters "is".

For a lot more on the subject, see this Guide to Python introspection by Patrick O'Brien - an article on IBM developerWorks:

http://www.ibm.com/developerworks/library/l-pyint/index.html

It is a bit dated (2002) but still interesting and useful.

Speaking of introspection in Python, you may also like to see :) my recent post:

Python's inspect module is powerful:

http://jugad2.blogspot.in/2013/05/python-inspect-module-is-powerful.html

- Vasudev Ram
dancingbison.com

No comments: