Wednesday, October 5, 2016

Get names and types of a Python module's attributes


By Vasudev Ram



Hi readers,

Today I thought of this simple Python utility while using introspection to look at some modules.

It looks at a module, and for each attribute in it, it tells you the name and type of the attribute. This is useful if you are exploring some new Python module (built-in or third-party), and you want, for example, to know all the functions or methods in it, so that you can further introspect those by printing their docstrings, using the form:
print(module_name.function_or_method_name.__doc__)
because the docstring of a Python function of method, if present, is a nice capsule summary of: its arguments, what it does, and its return value (i.e. its input, processing and output). So with such a docstring, in many cases, a reasonably experienced programmer may not even need to look up the actual Python docs for that function or method, before beginning to use it, thereby saving their time.

So here is the utility:
from __future__ import print_function

# mod_attrs_and_types.py 
# Purpose: To show the attribute names and types 
# of a Python module, to help with learning about it.
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: http://jugad2.blogspot.com
# Product store: https://gumroad.com/vasudevram

import sys

def attrs_and_types(mod_name):

    print('Attributes and their types for module {}:'.format(mod_name))
    print()
    for num, attr in enumerate(dir(eval(mod_name))):
        print("{idx}: {nam:30}  {typ}".format(
            idx=str(num + 1).rjust(4),
            nam=(mod_name + '.' + attr).ljust(30), 
            typ=type(eval(mod_name + '.' + attr))))

attrs_and_types(sys.__name__)
Running it like this:
$ python mod_attrs_and_types.py > out
gave this output:
Attributes and their types for module sys:

   1: sys.__displayhook__             <type 'builtin_function_or_method'>
   2: sys.__doc__                     <type 'str'>
   3: sys.__egginsert                 <type 'int'>
   4: sys.__excepthook__              <type 'builtin_function_or_method'>
   5: sys.__name__                    <type 'str'>
   6: sys.__package__                 <type 'NoneType'>
   7: sys.__plen                      <type 'int'>
   8: sys.__stderr__                  <type 'file'>
   9: sys.__stdin__                   <type 'file'>
  10: sys.__stdout__                  <type 'file'>
  11: sys._clear_type_cache           <type 'builtin_function_or_method'>
  12: sys._current_frames             <type 'builtin_function_or_method'>
  13: sys._getframe                   <type 'builtin_function_or_method'>
  14: sys._mercurial                  <type 'tuple'>
  15: sys.api_version                 <type 'int'>
  16: sys.argv                        <type 'list'>
  17: sys.builtin_module_names        <type 'tuple'>
  18: sys.byteorder                   <type 'str'>
  19: sys.call_tracing                <type 'builtin_function_or_method'>
  20: sys.callstats                   <type 'builtin_function_or_method'>
  21: sys.copyright                   <type 'str'>
  22: sys.displayhook                 <type 'builtin_function_or_method'>
  23: sys.dllhandle                   <type 'int'>
  24: sys.dont_write_bytecode         <type 'bool'>
  25: sys.exc_clear                   <type 'builtin_function_or_method'>
  26: sys.exc_info                    <type 'builtin_function_or_method'>
  27: sys.exc_type                    <type 'NoneType'>
  28: sys.excepthook                  <type 'builtin_function_or_method'>
  29: sys.exec_prefix                 <type 'str'>
  30: sys.executable                  <type 'str'>
  31: sys.exit                        <type 'builtin_function_or_method'>
  32: sys.flags                       <type 'sys.flags'>
  33: sys.float_info                  <type 'sys.float_info'>
  34: sys.float_repr_style            <type 'str'>
  35: sys.getcheckinterval            <type 'builtin_function_or_method'>
  36: sys.getdefaultencoding          <type 'builtin_function_or_method'>
  37: sys.getfilesystemencoding       <type 'builtin_function_or_method'>
  38: sys.getprofile                  <type 'builtin_function_or_method'>
  39: sys.getrecursionlimit           <type 'builtin_function_or_method'>
  40: sys.getrefcount                 <type 'builtin_function_or_method'>
  41: sys.getsizeof                   <type 'builtin_function_or_method'>
  42: sys.gettrace                    <type 'builtin_function_or_method'>
  43: sys.getwindowsversion           <type 'builtin_function_or_method'>
  44: sys.hexversion                  <type 'int'>
  45: sys.long_info                   <type 'sys.long_info'>
  46: sys.maxint                      <type 'int'>
  47: sys.maxsize                     <type 'int'>
  48: sys.maxunicode                  <type 'int'>
  49: sys.meta_path                   <type 'list'>
  50: sys.modules                     <type 'dict'>
  51: sys.path                        <type 'list'>
  52: sys.path_hooks                  <type 'list'>
  53: sys.path_importer_cache         <type 'dict'>
  54: sys.platform                    <type 'str'>
  55: sys.prefix                      <type 'str'>
  56: sys.py3kwarning                 <type 'bool'>
  57: sys.setcheckinterval            <type 'builtin_function_or_method'>
  58: sys.setprofile                  <type 'builtin_function_or_method'>
  59: sys.setrecursionlimit           <type 'builtin_function_or_method'>
  60: sys.settrace                    <type 'builtin_function_or_method'>
  61: sys.stderr                      <type 'file'>
  62: sys.stdin                       <type 'file'>
  63: sys.stdout                      <type 'file'>
  64: sys.subversion                  <type 'tuple'>
  65: sys.version                     <type 'str'>
  66: sys.version_info                <type 'sys.version_info'>
  67: sys.warnoptions                 <type 'list'>
  68: sys.winver                      <type 'str'>
There are other ways to do this, such as using the inspect module, but this is an easy way without inspect.

You can (e)grep for the pattern 'function|method' in the output, to get only the lines you want:

(If you haven't earlier, also check min_fgrep: minimal fgrep command in D.)
$ grep -E "function|method" out
1: sys.__displayhook__             <type 'builtin_function_or_method'>
   4: sys.__excepthook__              <type 'builtin_function_or_method'>
  11: sys._clear_type_cache           <type 'builtin_function_or_method'>
  12: sys._current_frames             <type 'builtin_function_or_method'>
  13: sys._getframe                   <type 'builtin_function_or_method'>
  19: sys.call_tracing                <type 'builtin_function_or_method'>
  20: sys.callstats                   <type 'builtin_function_or_method'>
  22: sys.displayhook                 <type 'builtin_function_or_method'>
  25: sys.exc_clear                   <type 'builtin_function_or_method'>
  26: sys.exc_info                    <type 'builtin_function_or_method'>
  28: sys.excepthook                  <type 'builtin_function_or_method'>
  31: sys.exit                        <type 'builtin_function_or_method'>
  35: sys.getcheckinterval            <type 'builtin_function_or_method'>
  36: sys.getdefaultencoding          <type 'builtin_function_or_method'>
  37: sys.getfilesystemencoding       <type 'builtin_function_or_method'>
  38: sys.getprofile                  <type 'builtin_function_or_method'>
  39: sys.getrecursionlimit           <type 'builtin_function_or_method'>
  40: sys.getrefcount                 <type 'builtin_function_or_method'>
  41: sys.getsizeof                   <type 'builtin_function_or_method'>
  42: sys.gettrace                    <type 'builtin_function_or_method'>
  43: sys.getwindowsversion           <type 'builtin_function_or_method'>
  57: sys.setcheckinterval            <type 'builtin_function_or_method'>
  58: sys.setprofile                  <type 'builtin_function_or_method'>
  59: sys.setrecursionlimit           <type 'builtin_function_or_method'>
  60: sys.settrace                    <type 'builtin_function_or_method'>
You can also (e)grep for a pattern or for alternative patterns:
$ grep -E "std(in|out)" out
   9: sys.__stdin__                   <type 'file'>
  10: sys.__stdout__                  <type 'file'>
  62: sys.stdin                       <type 'file'>
  63: sys.stdout                      <type 'file'>

The image at the top of the post is of a replica of a burning glass owned by Joseph Priestley, in his laboratory. If you don't remember your school physics, he is credited with having discovered oxygen.

- Enjoy.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

Managed WordPress Hosting by FlyWheel



No comments: