{article Dive into Python}{title} {text} {readmore}{/article}

introspection
the process of examining your own thoughts or feelings; the act of looking within oneself.


In computer programming, introspection refers to the ability to examine something to determine what it is, what it knows, and what it is capable of doing.

Run Mofule apihelper.py

Sample Usage of apihelper.py

"""Cheap and simple API helper

This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""

__author__ = "Mark Pilgrim (This email address is being protected from spambots. You need JavaScript enabled to view it.)"
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"

# While this is a good example script to teach about introspection,
# in real life it has been superceded by PyDoc, which is part of the
# standard library in Python 2.1 and later.
#
# Your IDE may already import the "help" function from pydoc
# automatically on startup; if not, do this:
#
# >>> from pydoc import help
#
# The help function in this module takes the object itself to get
# help on, but PyDoc can also take a string, like this:
#
# >>> help("string") # gets help on the string module
# >>> help("apihelper.help") # gets help on the function below
# >>> help() # enters an interactive help mode
#
# PyDoc can also act as an HTTP server to dynamically produce
# HTML-formatted documentation of any module in your path.
# That's wicked cool. Read more about PyDoc here:
# http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html

def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.

Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print ("\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList]))

if __name__ == "__main__":
print (help.__doc__)


Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ==================================================== RESTART ====================================================
>>>
Define the builtin 'help'.
This is a wrapper around pydoc.help (with a twist).


>>> from apihelper import info
>>> li = []
>>> info(li)
__add__ Return self+value.
__class__ list() -> new empty list list(iterable) -> new list initialized from iterable's items
__contains__ Return key in self.
__delattr__ Implement delattr(self, name).
__delitem__ Delete self[key].
__dir__ __dir__() -> list default dir() implementation
__eq__ Return self==value.
__format__ default object formatter
__ge__ __ge__=($self, value, /) -- Return self>=value.
__getattribute__ Return getattr(self, name).
__getitem__ x.__getitem__(y) <==> x[y]
__gt__ Return self>value.
__iadd__ Implement self+=value.
__imul__ Implement self*=value.
__init__ Initialize self. See help(type(self)) for accurate signature.
__iter__ Implement iter(self).
__le__ Return self<=value.
__len__ Return len(self).
__lt__ Return self<value.
__mul__ Return self*value.n
__ne__ Return self!=value.
__new__ Create and return a new object. See help(type) for accurate signature.
__reduce__ helper for pickle
__reduce_ex__ helper for pickle
__repr__ Return repr(self).
__reversed__ L.__reversed__() -- return a reverse iterator over the list
__rmul__ Return self*value.
__setattr__ Implement setattr(self, name, value).
__setitem__ Set self[key] to value.
__sizeof__ L.__sizeof__() -- size of L in memory, in bytes
__str__ Return str(self).
__subclasshook__ Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
append L.append(object) -> None -- append object to end
clear L.clear() -> None -- remove all items from L
copy L.copy() -> list -- a shallow copy of L
count L.count(value) -> integer -- return number of occurrences of value
extend L.extend(iterable) -> None -- extend list by appending elements from the iterable
index L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.
insert L.insert(index, object) -- insert object before index
pop L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.
remove L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present.
reverse L.reverse() -- reverse *IN PLACE*
sort L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*


Advanced Usage of apihelper.py

import odbchelper

info(odbchelper)

info(odbchelper, 30)

info(odbchelper, 30, 0)

introspection techniques

def interrogate(item):
"""Print useful information about item."""
if hasattr(item, '__name__'):
print ("NAME: ", item.__name__)
if hasattr(item, '__class__'):
print ("CLASS: ", item.__class__.__name__)
print ("ID: ", id(item))
print ("TYPE: ", type(item))
print ("VALUE: ", repr(item))
print ("CALLABLE:"),
if callable(item):
print ("Yes")
else:
print ("No")
if hasattr(item, '__doc__'):
doc = getattr(item, '__doc__')
doc = doc.strip() # Remove leading/trailing whitespace.
firstline = doc.split('\n')[0]
print ("DOC: ", firstline)

interrogate.py

>>> interrogate('a string') # String object
CLASS: str
ID: 59981488
TYPE: <class 'str'>
VALUE: 'a string'
CALLABLE:
No
DOC: str(object='') -> str
>>> interrogate(42) # Integer object
CLASS: int
ID: 1602520544
TYPE: <class 'int'>
VALUE: 42
CALLABLE:
No
DOC: int(x=0) -> integer
>>> interrogate(interrogate) # User-defined function object
NAME: interrogate
CLASS: function
ID: 59993080
TYPE: <class 'function'>
VALUE: <function interrogate at 0x0000000003936BF8>
CALLABLE:
Yes
DOC: Print useful information about item.
>>>