Posted By

magicrebirth on 12/22/09


Tagged

dir lambda collapse introspection callable getattr


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

saman


Python: Introspection function


 / Published in: Python
 

URL: diveintopython-5.4/html/power_of_introspection/index.html

The info function is designed to be used by you, the programmer, while working in the Python IDE. It takes any object that has functions or methods (like a module, which has functions, or a list, which has methods) and prints out the functions and their doc strings.

  1. def info(object, spacing=10, collapse=1):
  2. """Print methods and doc strings.
  3.  
  4. Takes module, class, list, dictionary, or string."""
  5. methodList = [method for method in dir(object) if callable(getattr(object, method))]
  6. processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
  7. print "\n".join(["%s %s" %
  8. (method.ljust(spacing),
  9. processFunc(str(getattr(object, method).__doc__)))
  10. for method in methodList])
  11.  
  12. if __name__ == "__main__":
  13. print info.__doc__

Report this snippet  

You need to login to post a comment.