Back to index

python3.2  3.2.2
Classes | Functions | Variables
inspect Namespace Reference

Classes

class  EndOfBlock
class  BlockFinder

Functions

def ismodule
def isclass
def ismethod
def ismethoddescriptor
def isdatadescriptor
def ismemberdescriptor
def isgetsetdescriptor
def isfunction
def isgeneratorfunction
def isgenerator
def istraceback
def isframe
def iscode
def isbuiltin
def isroutine
def isabstract
def getmembers
def classify_class_attrs
def getmro
def indentsize
def getdoc
def cleandoc
def getfile
def getmoduleinfo
def getmodulename
def getsourcefile
def getabsfile
def getmodule
def findsource
def getcomments
def getblock
def getsourcelines
def getsource
def walktree
def getclasstree
def getargs
def _getfullargs
def getargspec
def getfullargspec
def getargvalues
def formatannotation
def formatannotationrelativeto
def formatargspec
def formatargvalues
def getcallargs
def getframeinfo
def getlineno
def getouterframes
def getinnerframes
def currentframe
def stack
def trace
def _static_getmro
def _check_instance
def _check_class
def _is_type
def _shadowed_dict
def getattr_static
def getgeneratorstate

Variables

string __author__ = 'Ka-Ping Yee <ping@lfw.org>'
string __date__ = '1 Jan 2001'
tuple mod_dict = globals()
int TPFLAGS_IS_ABSTRACT = 1
tuple Attribute = namedtuple('Attribute', 'name kind defining_class object')
tuple ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
dictionary modulesbyfile = {}
dictionary _filesbymodname = {}
tuple Arguments = namedtuple('Arguments', 'args, varargs, varkw')
tuple ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
tuple FullArgSpec
tuple ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
tuple Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
tuple _sentinel = object()
string GEN_CREATED = 'GEN_CREATED'
string GEN_RUNNING = 'GEN_RUNNING'
string GEN_SUSPENDED = 'GEN_SUSPENDED'
string GEN_CLOSED = 'GEN_CLOSED'

Detailed Description

Get useful information from live Python objects.

This module encapsulates the interface provided by the internal special
attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
It also provides some help for examining source code and class layout.

Here are some of the useful functions provided by this module:

    ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
isroutine() - check object types
    getmembers() - get members of an object that satisfy a given condition

    getfile(), getsourcefile(), getsource() - find an object's source code
    getdoc(), getcomments() - get documentation on an object
    getmodule() - determine the module that an object came from
    getclasstree() - arrange classes so as to represent their hierarchy

    getargspec(), getargvalues(), getcallargs() - get info about function arguments
    getfullargspec() - same, with support for Python-3000 features
    formatargspec(), formatargvalues() - format an argument spec
    getouterframes(), getinnerframes() - get info about frames
    currentframe() - get the current stack frame
    stack(), trace() - get info about frames on the stack or in a traceback

Function Documentation

def inspect._check_class (   klass,
  attr 
) [private]

Definition at line 1085 of file inspect.py.

01085 
01086 def _check_class(klass, attr):
01087     for entry in _static_getmro(klass):
01088         if not _shadowed_dict(type(entry)):
01089             try:
01090                 return entry.__dict__[attr]
01091             except KeyError:
01092                 pass
01093     return _sentinel

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect._check_instance (   obj,
  attr 
) [private]

Definition at line 1076 of file inspect.py.

01076 
01077 def _check_instance(obj, attr):
01078     instance_dict = {}
01079     try:
01080         instance_dict = object.__getattribute__(obj, "__dict__")
01081     except AttributeError:
01082         pass
01083     return dict.get(instance_dict, attr, _sentinel)
01084 

Here is the caller graph for this function:

def inspect._getfullargs (   co) [private]
Get information about the arguments accepted by a code object.

Four things are returned: (args, varargs, kwonlyargs, varkw), where
'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
and 'varkw' are the names of the * and ** arguments or None.

Definition at line 749 of file inspect.py.

00749 
00750 def _getfullargs(co):
00751     """Get information about the arguments accepted by a code object.
00752 
00753     Four things are returned: (args, varargs, kwonlyargs, varkw), where
00754     'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
00755     and 'varkw' are the names of the * and ** arguments or None."""
00756 
00757     if not iscode(co):
00758         raise TypeError('{!r} is not a code object'.format(co))
00759 
00760     nargs = co.co_argcount
00761     names = co.co_varnames
00762     nkwargs = co.co_kwonlyargcount
00763     args = list(names[:nargs])
00764     kwonlyargs = list(names[nargs:nargs+nkwargs])
00765     step = 0
00766 
00767     nargs += nkwargs
00768     varargs = None
00769     if co.co_flags & CO_VARARGS:
00770         varargs = co.co_varnames[nargs]
00771         nargs = nargs + 1
00772     varkw = None
00773     if co.co_flags & CO_VARKEYWORDS:
00774         varkw = co.co_varnames[nargs]
00775     return args, varargs, kwonlyargs, varkw
00776 

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect._is_type (   obj) [private]

Definition at line 1094 of file inspect.py.

01094 
01095 def _is_type(obj):
01096     try:
01097         _static_getmro(obj)
01098     except TypeError:
01099         return False
01100     return True

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect._shadowed_dict (   klass) [private]

Definition at line 1101 of file inspect.py.

01101 
01102 def _shadowed_dict(klass):
01103     dict_attr = type.__dict__["__dict__"]
01104     for entry in _static_getmro(klass):
01105         try:
01106             class_dict = dict_attr.__get__(entry)["__dict__"]
01107         except KeyError:
01108             pass
01109         else:
01110             if not (type(class_dict) is types.GetSetDescriptorType and
01111                     class_dict.__name__ == "__dict__" and
01112                     class_dict.__objclass__ is entry):
01113                 return True
01114     return False

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect._static_getmro (   klass) [private]

Definition at line 1073 of file inspect.py.

01073 
01074 def _static_getmro(klass):
01075     return type.__dict__['__mro__'].__get__(klass)

Here is the caller graph for this function:

Return list of attribute-descriptor tuples.

For each name in dir(cls), the return list contains a 4-tuple
with these elements:

    0. The name (a string).

    1. The kind of attribute this is, one of these strings:
           'class method'    created via classmethod()
           'static method'   created via staticmethod()
           'property'        created via property()
           'method'          any other flavor of method
           'data'            not a method

    2. The class which defined this attribute (a class).

    3. The object as obtained directly from the defining class's
       __dict__, not via getattr.  This is especially important for
       data attributes:  C.data is just a data object, but
       C.__dict__['data'] may be a data descriptor with additional
       info, like a __doc__ string.

Definition at line 270 of file inspect.py.

00270 
00271 def classify_class_attrs(cls):
00272     """Return list of attribute-descriptor tuples.
00273 
00274     For each name in dir(cls), the return list contains a 4-tuple
00275     with these elements:
00276 
00277         0. The name (a string).
00278 
00279         1. The kind of attribute this is, one of these strings:
00280                'class method'    created via classmethod()
00281                'static method'   created via staticmethod()
00282                'property'        created via property()
00283                'method'          any other flavor of method
00284                'data'            not a method
00285 
00286         2. The class which defined this attribute (a class).
00287 
00288         3. The object as obtained directly from the defining class's
00289            __dict__, not via getattr.  This is especially important for
00290            data attributes:  C.data is just a data object, but
00291            C.__dict__['data'] may be a data descriptor with additional
00292            info, like a __doc__ string.
00293     """
00294 
00295     mro = getmro(cls)
00296     names = dir(cls)
00297     result = []
00298     for name in names:
00299         # Get the object associated with the name.
00300         # Getting an obj from the __dict__ sometimes reveals more than
00301         # using getattr.  Static and class methods are dramatic examples.
00302         if name in cls.__dict__:
00303             obj = cls.__dict__[name]
00304         else:
00305             obj = getattr(cls, name)
00306 
00307         # Figure out where it was defined.
00308         homecls = getattr(obj, "__objclass__", None)
00309         if homecls is None:
00310             # search the dicts.
00311             for base in mro:
00312                 if name in base.__dict__:
00313                     homecls = base
00314                     break
00315 
00316         # Get the object again, in order to get it from the defining
00317         # __dict__ instead of via getattr (if possible).
00318         if homecls is not None and name in homecls.__dict__:
00319             obj = homecls.__dict__[name]
00320 
00321         # Also get the object via getattr.
00322         obj_via_getattr = getattr(cls, name)
00323 
00324         # Classify the object.
00325         if isinstance(obj, staticmethod):
00326             kind = "static method"
00327         elif isinstance(obj, classmethod):
00328             kind = "class method"
00329         elif isinstance(obj, property):
00330             kind = "property"
00331         elif (isfunction(obj_via_getattr) or
00332               ismethoddescriptor(obj_via_getattr)):
00333             kind = "method"
00334         else:
00335             kind = "data"
00336 
00337         result.append(Attribute(name, kind, homecls, obj))
00338 
00339     return result
00340 
00341 # ----------------------------------------------------------- class helpers

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.cleandoc (   doc)
Clean up indentation from docstrings.

Any whitespace that can be uniformly removed from the second line
onwards is removed.

Definition at line 366 of file inspect.py.

00366 
00367 def cleandoc(doc):
00368     """Clean up indentation from docstrings.
00369 
00370     Any whitespace that can be uniformly removed from the second line
00371     onwards is removed."""
00372     try:
00373         lines = doc.expandtabs().split('\n')
00374     except UnicodeError:
00375         return None
00376     else:
00377         # Find minimum indentation of any non-blank lines after first line.
00378         margin = sys.maxsize
00379         for line in lines[1:]:
00380             content = len(line.lstrip())
00381             if content:
00382                 indent = len(line) - content
00383                 margin = min(margin, indent)
00384         # Remove indentation.
00385         if lines:
00386             lines[0] = lines[0].lstrip()
00387         if margin < sys.maxsize:
00388             for i in range(1, len(lines)): lines[i] = lines[i][margin:]
00389         # Remove any trailing or leading blank lines.
00390         while lines and not lines[-1]:
00391             lines.pop()
00392         while lines and not lines[0]:
00393             lines.pop(0)
00394         return '\n'.join(lines)

Here is the call graph for this function:

Here is the caller graph for this function:

Return the frame of the caller or None if this is not possible.

Definition at line 1056 of file inspect.py.

01056 
01057 def currentframe():
01058     """Return the frame of the caller or None if this is not possible."""
01059     return sys._getframe(1) if hasattr(sys, "_getframe") else None

Here is the caller graph for this function:

def inspect.findsource (   object)
Return the entire source file and starting line number for an object.

The argument may be a module, class, method, function, traceback, frame,
or code object.  The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list.  An IOError
is raised if the source code cannot be retrieved.

Definition at line 514 of file inspect.py.

00514 
00515 def findsource(object):
00516     """Return the entire source file and starting line number for an object.
00517 
00518     The argument may be a module, class, method, function, traceback, frame,
00519     or code object.  The source code is returned as a list of all the lines
00520     in the file and the line number indexes a line in that list.  An IOError
00521     is raised if the source code cannot be retrieved."""
00522 
00523     file = getfile(object)
00524     sourcefile = getsourcefile(object)
00525     if not sourcefile and file[0] + file[-1] != '<>':
00526         raise IOError('source code not available')
00527     file = sourcefile if sourcefile else file
00528 
00529     module = getmodule(object, file)
00530     if module:
00531         lines = linecache.getlines(file, module.__dict__)
00532     else:
00533         lines = linecache.getlines(file)
00534     if not lines:
00535         raise IOError('could not get source code')
00536 
00537     if ismodule(object):
00538         return lines, 0
00539 
00540     if isclass(object):
00541         name = object.__name__
00542         pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
00543         # make some effort to find the best matching class definition:
00544         # use the one with the least indentation, which is the one
00545         # that's most probably not inside a function definition.
00546         candidates = []
00547         for i in range(len(lines)):
00548             match = pat.match(lines[i])
00549             if match:
00550                 # if it's at toplevel, it's already the best one
00551                 if lines[i][0] == 'c':
00552                     return lines, i
00553                 # else add whitespace to candidate list
00554                 candidates.append((match.group(1), i))
00555         if candidates:
00556             # this will sort by whitespace, and by line number,
00557             # less whitespace first
00558             candidates.sort()
00559             return lines, candidates[0][1]
00560         else:
00561             raise IOError('could not find class definition')
00562 
00563     if ismethod(object):
00564         object = object.__func__
00565     if isfunction(object):
00566         object = object.__code__
00567     if istraceback(object):
00568         object = object.tb_frame
00569     if isframe(object):
00570         object = object.f_code
00571     if iscode(object):
00572         if not hasattr(object, 'co_firstlineno'):
00573             raise IOError('could not find function definition')
00574         lnum = object.co_firstlineno - 1
00575         pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
00576         while lnum > 0:
00577             if pat.match(lines[lnum]): break
00578             lnum = lnum - 1
00579         return lines, lnum
00580     raise IOError('could not find code object')

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.formatannotation (   annotation,
  base_module = None 
)

Definition at line 838 of file inspect.py.

00838 
00839 def formatannotation(annotation, base_module=None):
00840     if isinstance(annotation, type):
00841         if annotation.__module__ in ('builtins', base_module):
00842             return annotation.__name__
00843         return annotation.__module__+'.'+annotation.__name__
00844     return repr(annotation)

Here is the caller graph for this function:

Definition at line 845 of file inspect.py.

00845 
00846 def formatannotationrelativeto(object):
00847     module = getattr(object, '__module__', None)
00848     def _formatannotation(annotation):
00849         return formatannotation(annotation, module)
00850     return _formatannotation

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.formatargspec (   args,
  varargs = None,
  varkw = None,
  defaults = None,
  kwonlyargs = (),
  kwonlydefaults = {},
  annotations = {},
  formatarg = str,
  formatvarargs = lambda name: '*' + name,
  formatvarkw = lambda name: '**' + name,
  formatvalue = lambda value: '=' + repr(value),
  formatreturns = lambda text: ' -> ' + text,
  formatannotation = formatannotation 
)
Format an argument spec from the values returned by getargspec
or getfullargspec.

The first seven arguments are (args, varargs, varkw, defaults,
kwonlyargs, kwonlydefaults, annotations).  The other five arguments
are the corresponding optional formatting functions that are called to
turn names and values into strings.  The last argument is an optional
function to format the sequence of arguments.

Definition at line 858 of file inspect.py.

00858 
00859                   formatannotation=formatannotation):
00860     """Format an argument spec from the values returned by getargspec
00861     or getfullargspec.
00862 
00863     The first seven arguments are (args, varargs, varkw, defaults,
00864     kwonlyargs, kwonlydefaults, annotations).  The other five arguments
00865     are the corresponding optional formatting functions that are called to
00866     turn names and values into strings.  The last argument is an optional
00867     function to format the sequence of arguments."""
00868     def formatargandannotation(arg):
00869         result = formatarg(arg)
00870         if arg in annotations:
00871             result += ': ' + formatannotation(annotations[arg])
00872         return result
00873     specs = []
00874     if defaults:
00875         firstdefault = len(args) - len(defaults)
00876     for i, arg in enumerate(args):
00877         spec = formatargandannotation(arg)
00878         if defaults and i >= firstdefault:
00879             spec = spec + formatvalue(defaults[i - firstdefault])
00880         specs.append(spec)
00881     if varargs is not None:
00882         specs.append(formatvarargs(formatargandannotation(varargs)))
00883     else:
00884         if kwonlyargs:
00885             specs.append('*')
00886     if kwonlyargs:
00887         for kwonlyarg in kwonlyargs:
00888             spec = formatargandannotation(kwonlyarg)
00889             if kwonlydefaults and kwonlyarg in kwonlydefaults:
00890                 spec += formatvalue(kwonlydefaults[kwonlyarg])
00891             specs.append(spec)
00892     if varkw is not None:
00893         specs.append(formatvarkw(formatargandannotation(varkw)))
00894     result = '(' + ', '.join(specs) + ')'
00895     if 'return' in annotations:
00896         result += formatreturns(formatannotation(annotations['return']))
00897     return result

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.formatargvalues (   args,
  varargs,
  varkw,
  locals,
  formatarg = str,
  formatvarargs = lambda name: '*' + name,
  formatvarkw = lambda name: '**' + name,
  formatvalue = lambda value: '=' + repr(value) 
)
Format an argument spec from the 4 values returned by getargvalues.

The first four arguments are (args, varargs, varkw, locals).  The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings.  The ninth
argument is an optional function to format the sequence of arguments.

Definition at line 902 of file inspect.py.

00902 
00903                     formatvalue=lambda value: '=' + repr(value)):
00904     """Format an argument spec from the 4 values returned by getargvalues.
00905 
00906     The first four arguments are (args, varargs, varkw, locals).  The
00907     next four arguments are the corresponding optional formatting functions
00908     that are called to turn names and values into strings.  The ninth
00909     argument is an optional function to format the sequence of arguments."""
00910     def convert(name, locals=locals,
00911                 formatarg=formatarg, formatvalue=formatvalue):
00912         return formatarg(name) + formatvalue(locals[name])
00913     specs = []
00914     for i in range(len(args)):
00915         specs.append(convert(args[i]))
00916     if varargs:
00917         specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
00918     if varkw:
00919         specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
00920     return '(' + ', '.join(specs) + ')'

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getabsfile (   object,
  _filename = None 
)
Return an absolute path to the source or compiled file for an object.

The idea is for each object to have a unique origin, so this routine
normalizes the result as much as possible.

Definition at line 456 of file inspect.py.

00456 
00457 def getabsfile(object, _filename=None):
00458     """Return an absolute path to the source or compiled file for an object.
00459 
00460     The idea is for each object to have a unique origin, so this routine
00461     normalizes the result as much as possible."""
00462     if _filename is None:
00463         _filename = getsourcefile(object) or getfile(object)
00464     return os.path.normcase(os.path.abspath(_filename))

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getargs (   co)
Get information about the arguments accepted by a code object.

Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None.

Definition at line 739 of file inspect.py.

00739 
00740 def getargs(co):
00741     """Get information about the arguments accepted by a code object.
00742 
00743     Three things are returned: (args, varargs, varkw), where
00744     'args' is the list of argument names. Keyword-only arguments are
00745     appended. 'varargs' and 'varkw' are the names of the * and **
00746     arguments or None."""
00747     args, varargs, kwonlyargs, varkw = _getfullargs(co)
00748     return Arguments(args + kwonlyargs, varargs, varkw)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getargspec (   func)
Get the names and default values of a function's arguments.

A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names.
'args' will include keyword-only argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.

Use the getfullargspec() API for Python-3000 code, as annotations
and keyword arguments are supported. getargspec() will raise ValueError
if the func has either annotations or keyword arguments.

Definition at line 779 of file inspect.py.

00779 
00780 def getargspec(func):
00781     """Get the names and default values of a function's arguments.
00782 
00783     A tuple of four things is returned: (args, varargs, varkw, defaults).
00784     'args' is a list of the argument names.
00785     'args' will include keyword-only argument names.
00786     'varargs' and 'varkw' are the names of the * and ** arguments or None.
00787     'defaults' is an n-tuple of the default values of the last n arguments.
00788 
00789     Use the getfullargspec() API for Python-3000 code, as annotations
00790     and keyword arguments are supported. getargspec() will raise ValueError
00791     if the func has either annotations or keyword arguments.
00792     """
00793 
00794     args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
00795         getfullargspec(func)
00796     if kwonlyargs or ann:
00797         raise ValueError("Function has keyword-only arguments or annotations"
00798                          ", use getfullargspec() API which can support them")
00799     return ArgSpec(args, varargs, varkw, defaults)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getargvalues (   frame)
Get information about arguments passed into a particular frame.

A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame.

Definition at line 828 of file inspect.py.

00828 
00829 def getargvalues(frame):
00830     """Get information about arguments passed into a particular frame.
00831 
00832     A tuple of four things is returned: (args, varargs, varkw, locals).
00833     'args' is a list of the argument names.
00834     'varargs' and 'varkw' are the names of the * and ** arguments or None.
00835     'locals' is the locals dictionary of the given frame."""
00836     args, varargs, varkw = getargs(frame.f_code)
00837     return ArgInfo(args, varargs, varkw, frame.f_locals)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getattr_static (   obj,
  attr,
  default = _sentinel 
)
Retrieve attributes without triggering dynamic lookup via the
   descriptor protocol,  __getattr__ or __getattribute__.

   Note: this function may not be able to retrieve all attributes
   that getattr can fetch (like dynamically created attributes)
   and may find attributes that getattr can't (like descriptors
   that raise AttributeError). It can also return descriptor objects
   instead of instance members in some cases. See the
   documentation for details.

Definition at line 1115 of file inspect.py.

01115 
01116 def getattr_static(obj, attr, default=_sentinel):
01117     """Retrieve attributes without triggering dynamic lookup via the
01118        descriptor protocol,  __getattr__ or __getattribute__.
01119 
01120        Note: this function may not be able to retrieve all attributes
01121        that getattr can fetch (like dynamically created attributes)
01122        and may find attributes that getattr can't (like descriptors
01123        that raise AttributeError). It can also return descriptor objects
01124        instead of instance members in some cases. See the
01125        documentation for details.
01126     """
01127     instance_result = _sentinel
01128     if not _is_type(obj):
01129         klass = type(obj)
01130         if not _shadowed_dict(klass):
01131             instance_result = _check_instance(obj, attr)
01132     else:
01133         klass = obj
01134 
01135     klass_result = _check_class(klass, attr)
01136 
01137     if instance_result is not _sentinel and klass_result is not _sentinel:
01138         if (_check_class(type(klass_result), '__get__') is not _sentinel and
01139             _check_class(type(klass_result), '__set__') is not _sentinel):
01140             return klass_result
01141 
01142     if instance_result is not _sentinel:
01143         return instance_result
01144     if klass_result is not _sentinel:
01145         return klass_result
01146 
01147     if obj is klass:
01148         # for types we check the metaclass too
01149         for entry in _static_getmro(type(klass)):
01150             try:
01151                 return entry.__dict__[attr]
01152             except KeyError:
01153                 pass
01154     if default is not _sentinel:
01155         return default
01156     raise AttributeError(attr)
01157 

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getblock (   lines)
Extract the block of code at the top of the given list of lines.

Definition at line 667 of file inspect.py.

00667 
00668 def getblock(lines):
00669     """Extract the block of code at the top of the given list of lines."""
00670     blockfinder = BlockFinder()
00671     try:
00672         tokens = tokenize.generate_tokens(iter(lines).__next__)
00673         for _token in tokens:
00674             blockfinder.tokeneater(*_token)
00675     except (EndOfBlock, IndentationError):
00676         pass
00677     return lines[:blockfinder.last]

Here is the caller graph for this function:

def inspect.getcallargs (   func,
  positional,
  named 
)
Get the mapping of arguments to values.

A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'.

Definition at line 921 of file inspect.py.

00921 
00922 def getcallargs(func, *positional, **named):
00923     """Get the mapping of arguments to values.
00924 
00925     A dict is returned, with keys the function argument names (including the
00926     names of the * and ** arguments, if any), and values the respective bound
00927     values from 'positional' and 'named'."""
00928     spec = getfullargspec(func)
00929     args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
00930     f_name = func.__name__
00931     arg2value = {}
00932 
00933     if ismethod(func) and func.__self__ is not None:
00934         # implicit 'self' (or 'cls' for classmethods) argument
00935         positional = (func.__self__,) + positional
00936     num_pos = len(positional)
00937     num_total = num_pos + len(named)
00938     num_args = len(args)
00939     num_defaults = len(defaults) if defaults else 0
00940     for arg, value in zip(args, positional):
00941         arg2value[arg] = value
00942     if varargs:
00943         if num_pos > num_args:
00944             arg2value[varargs] = positional[-(num_pos-num_args):]
00945         else:
00946             arg2value[varargs] = ()
00947     elif 0 < num_args < num_pos:
00948         raise TypeError('%s() takes %s %d positional %s (%d given)' % (
00949             f_name, 'at most' if defaults else 'exactly', num_args,
00950             'arguments' if num_args > 1 else 'argument', num_total))
00951     elif num_args == 0 and num_total:
00952         if varkw or kwonlyargs:
00953             if num_pos:
00954                 # XXX: We should use num_pos, but Python also uses num_total:
00955                 raise TypeError('%s() takes exactly 0 positional arguments '
00956                                 '(%d given)' % (f_name, num_total))
00957         else:
00958             raise TypeError('%s() takes no arguments (%d given)' %
00959                             (f_name, num_total))
00960 
00961     for arg in itertools.chain(args, kwonlyargs):
00962         if arg in named:
00963             if arg in arg2value:
00964                 raise TypeError("%s() got multiple values for keyword "
00965                                 "argument '%s'" % (f_name, arg))
00966             else:
00967                 arg2value[arg] = named.pop(arg)
00968     for kwonlyarg in kwonlyargs:
00969         if kwonlyarg not in arg2value:
00970             try:
00971                 arg2value[kwonlyarg] = kwonlydefaults[kwonlyarg]
00972             except KeyError:
00973                 raise TypeError("%s() needs keyword-only argument %s" %
00974                                 (f_name, kwonlyarg))
00975     if defaults:    # fill in any missing values with the defaults
00976         for arg, value in zip(args[-num_defaults:], defaults):
00977             if arg not in arg2value:
00978                 arg2value[arg] = value
00979     if varkw:
00980         arg2value[varkw] = named
00981     elif named:
00982         unexpected = next(iter(named))
00983         raise TypeError("%s() got an unexpected keyword argument '%s'" %
00984                         (f_name, unexpected))
00985     unassigned = num_args - len([arg for arg in args if arg in arg2value])
00986     if unassigned:
00987         num_required = num_args - num_defaults
00988         raise TypeError('%s() takes %s %d %s (%d given)' % (
00989             f_name, 'at least' if defaults else 'exactly', num_required,
00990             'arguments' if num_required > 1 else 'argument', num_total))
00991     return arg2value
00992 
00993 # -------------------------------------------------- stack frame extraction

Here is the call graph for this function:

def inspect.getclasstree (   classes,
  unique = False 
)
Arrange the given list of classes into a hierarchy of nested lists.

Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list.  Each entry is a 2-tuple
containing a class and a tuple of its base classes.  If the 'unique'
argument is true, exactly one entry appears in the returned structure
for each class in the given list.  Otherwise, classes using multiple
inheritance and their descendants will appear multiple times.

Definition at line 711 of file inspect.py.

00711 
00712 def getclasstree(classes, unique=False):
00713     """Arrange the given list of classes into a hierarchy of nested lists.
00714 
00715     Where a nested list appears, it contains classes derived from the class
00716     whose entry immediately precedes the list.  Each entry is a 2-tuple
00717     containing a class and a tuple of its base classes.  If the 'unique'
00718     argument is true, exactly one entry appears in the returned structure
00719     for each class in the given list.  Otherwise, classes using multiple
00720     inheritance and their descendants will appear multiple times."""
00721     children = {}
00722     roots = []
00723     for c in classes:
00724         if c.__bases__:
00725             for parent in c.__bases__:
00726                 if not parent in children:
00727                     children[parent] = []
00728                 children[parent].append(c)
00729                 if unique and parent in classes: break
00730         elif c not in roots:
00731             roots.append(c)
00732     for parent in children:
00733         if parent not in classes:
00734             roots.append(parent)
00735     return walktree(roots, children, None)
00736 
# ------------------------------------------------ argument list extraction

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getcomments (   object)
Get lines of comments immediately preceding an object's source code.

Returns None when source can't be found.

Definition at line 581 of file inspect.py.

00581 
00582 def getcomments(object):
00583     """Get lines of comments immediately preceding an object's source code.
00584 
00585     Returns None when source can't be found.
00586     """
00587     try:
00588         lines, lnum = findsource(object)
00589     except (IOError, TypeError):
00590         return None
00591 
00592     if ismodule(object):
00593         # Look for a comment block at the top of the file.
00594         start = 0
00595         if lines and lines[0][:2] == '#!': start = 1
00596         while start < len(lines) and lines[start].strip() in ('', '#'):
00597             start = start + 1
00598         if start < len(lines) and lines[start][:1] == '#':
00599             comments = []
00600             end = start
00601             while end < len(lines) and lines[end][:1] == '#':
00602                 comments.append(lines[end].expandtabs())
00603                 end = end + 1
00604             return ''.join(comments)
00605 
00606     # Look for a preceding block of comments at the same indentation.
00607     elif lnum > 0:
00608         indent = indentsize(lines[lnum])
00609         end = lnum - 1
00610         if end >= 0 and lines[end].lstrip()[:1] == '#' and \
00611             indentsize(lines[end]) == indent:
00612             comments = [lines[end].expandtabs().lstrip()]
00613             if end > 0:
00614                 end = end - 1
00615                 comment = lines[end].expandtabs().lstrip()
00616                 while comment[:1] == '#' and indentsize(lines[end]) == indent:
00617                     comments[:0] = [comment]
00618                     end = end - 1
00619                     if end < 0: break
00620                     comment = lines[end].expandtabs().lstrip()
00621             while comments and comments[0].strip() == '#':
00622                 comments[:1] = []
00623             while comments and comments[-1].strip() == '#':
00624                 comments[-1:] = []
00625             return ''.join(comments)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getdoc (   object)
Get the documentation string for an object.

All tabs are expanded to spaces.  To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed.

Definition at line 352 of file inspect.py.

00352 
00353 def getdoc(object):
00354     """Get the documentation string for an object.
00355 
00356     All tabs are expanded to spaces.  To clean up docstrings that are
00357     indented to line up with blocks of code, any whitespace than can be
00358     uniformly removed from the second line onwards is removed."""
00359     try:
00360         doc = object.__doc__
00361     except AttributeError:
00362         return None
00363     if not isinstance(doc, str):
00364         return None
00365     return cleandoc(doc)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getfile (   object)
Work out which source or compiled file an object was defined in.

Definition at line 395 of file inspect.py.

00395 
00396 def getfile(object):
00397     """Work out which source or compiled file an object was defined in."""
00398     if ismodule(object):
00399         if hasattr(object, '__file__'):
00400             return object.__file__
00401         raise TypeError('{!r} is a built-in module'.format(object))
00402     if isclass(object):
00403         object = sys.modules.get(object.__module__)
00404         if hasattr(object, '__file__'):
00405             return object.__file__
00406         raise TypeError('{!r} is a built-in class'.format(object))
00407     if ismethod(object):
00408         object = object.__func__
00409     if isfunction(object):
00410         object = object.__code__
00411     if istraceback(object):
00412         object = object.tb_frame
00413     if isframe(object):
00414         object = object.f_code
00415     if iscode(object):
00416         return object.co_filename
00417     raise TypeError('{!r} is not a module, class, method, '
00418                     'function, traceback, frame, or code object'.format(object))

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getframeinfo (   frame,
  context = 1 
)
Get information about a frame or traceback object.

A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
The optional second argument specifies the number of lines of context
to return, which are centered around the current line.

Definition at line 996 of file inspect.py.

00996 
00997 def getframeinfo(frame, context=1):
00998     """Get information about a frame or traceback object.
00999 
01000     A tuple of five things is returned: the filename, the line number of
01001     the current line, the function name, a list of lines of context from
01002     the source code, and the index of the current line within that list.
01003     The optional second argument specifies the number of lines of context
01004     to return, which are centered around the current line."""
01005     if istraceback(frame):
01006         lineno = frame.tb_lineno
01007         frame = frame.tb_frame
01008     else:
01009         lineno = frame.f_lineno
01010     if not isframe(frame):
01011         raise TypeError('{!r} is not a frame or traceback object'.format(frame))
01012 
01013     filename = getsourcefile(frame) or getfile(frame)
01014     if context > 0:
01015         start = lineno - 1 - context//2
01016         try:
01017             lines, lnum = findsource(frame)
01018         except IOError:
01019             lines = index = None
01020         else:
01021             start = max(start, 1)
01022             start = max(0, min(start, len(lines) - context))
01023             lines = lines[start:start+context]
01024             index = lineno - 1 - start
01025     else:
01026         lines = index = None
01027 
01028     return Traceback(filename, lineno, frame.f_code.co_name, lines, index)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getfullargspec (   func)
Get the names and default values of a function's arguments.

A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
'kwonlyargs' is a list of keyword-only argument names.
'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
'annotations' is a dictionary mapping argument names to annotations.

The first four items in the tuple correspond to getargspec().

Definition at line 803 of file inspect.py.

00803 
00804 def getfullargspec(func):
00805     """Get the names and default values of a function's arguments.
00806 
00807     A tuple of seven things is returned:
00808     (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
00809     'args' is a list of the argument names.
00810     'varargs' and 'varkw' are the names of the * and ** arguments or None.
00811     'defaults' is an n-tuple of the default values of the last n arguments.
00812     'kwonlyargs' is a list of keyword-only argument names.
00813     'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
00814     'annotations' is a dictionary mapping argument names to annotations.
00815 
00816     The first four items in the tuple correspond to getargspec().
00817     """
00818 
00819     if ismethod(func):
00820         func = func.__func__
00821     if not isfunction(func):
00822         raise TypeError('{!r} is not a Python function'.format(func))
00823     args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
00824     return FullArgSpec(args, varargs, varkw, func.__defaults__,
00825             kwonlyargs, func.__kwdefaults__, func.__annotations__)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getgeneratorstate (   generator)
Get current state of a generator-iterator.

Possible states are:
  GEN_CREATED: Waiting to start execution.
  GEN_RUNNING: Currently being executed by the interpreter.
  GEN_SUSPENDED: Currently suspended at a yield expression.
  GEN_CLOSED: Execution has completed.

Definition at line 1163 of file inspect.py.

01163 
01164 def getgeneratorstate(generator):
01165     """Get current state of a generator-iterator.
01166 
01167     Possible states are:
01168       GEN_CREATED: Waiting to start execution.
01169       GEN_RUNNING: Currently being executed by the interpreter.
01170       GEN_SUSPENDED: Currently suspended at a yield expression.
01171       GEN_CLOSED: Execution has completed.
01172     """
01173     if generator.gi_running:
01174         return GEN_RUNNING
01175     if generator.gi_frame is None:
01176         return GEN_CLOSED
01177     if generator.gi_frame.f_lasti == -1:
01178         return GEN_CREATED
01179     return GEN_SUSPENDED

Here is the caller graph for this function:

def inspect.getinnerframes (   tb,
  context = 1 
)
Get a list of records for a traceback's frame and all lower frames.

Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context.

Definition at line 1045 of file inspect.py.

01045 
01046 def getinnerframes(tb, context=1):
01047     """Get a list of records for a traceback's frame and all lower frames.
01048 
01049     Each record contains a frame object, filename, line number, function
01050     name, a list of lines of context, and index within the context."""
01051     framelist = []
01052     while tb:
01053         framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
01054         tb = tb.tb_next
01055     return framelist

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getlineno (   frame)
Get the line number from a frame object, allowing for optimization.

Definition at line 1029 of file inspect.py.

01029 
01030 def getlineno(frame):
01031     """Get the line number from a frame object, allowing for optimization."""
01032     # FrameType.f_lineno is now a descriptor that grovels co_lnotab
01033     return frame.f_lineno

def inspect.getmembers (   object,
  predicate = None 
)
Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate.

Definition at line 254 of file inspect.py.

00254 
00255 def getmembers(object, predicate=None):
00256     """Return all members of an object as (name, value) pairs sorted by name.
00257     Optionally, only return members that satisfy a given predicate."""
00258     results = []
00259     for key in dir(object):
00260         try:
00261             value = getattr(object, key)
00262         except AttributeError:
00263             continue
00264         if not predicate or predicate(value):
00265             results.append((key, value))
00266     results.sort()
00267     return results

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getmodule (   object,
  _filename = None 
)
Return the module an object was defined in, or None if not found.

Definition at line 468 of file inspect.py.

00468 
00469 def getmodule(object, _filename=None):
00470     """Return the module an object was defined in, or None if not found."""
00471     if ismodule(object):
00472         return object
00473     if hasattr(object, '__module__'):
00474         return sys.modules.get(object.__module__)
00475     # Try the filename to modulename cache
00476     if _filename is not None and _filename in modulesbyfile:
00477         return sys.modules.get(modulesbyfile[_filename])
00478     # Try the cache again with the absolute file name
00479     try:
00480         file = getabsfile(object, _filename)
00481     except TypeError:
00482         return None
00483     if file in modulesbyfile:
00484         return sys.modules.get(modulesbyfile[file])
00485     # Update the filename to module name cache and check yet again
00486     # Copy sys.modules in order to cope with changes while iterating
00487     for modname, module in sys.modules.items():
00488         if ismodule(module) and hasattr(module, '__file__'):
00489             f = module.__file__
00490             if f == _filesbymodname.get(modname, None):
00491                 # Have already mapped this module, so skip it
00492                 continue
00493             _filesbymodname[modname] = f
00494             f = getabsfile(module)
00495             # Always map to the name the module knows itself by
00496             modulesbyfile[f] = modulesbyfile[
00497                 os.path.realpath(f)] = module.__name__
00498     if file in modulesbyfile:
00499         return sys.modules.get(modulesbyfile[file])
00500     # Check the main module
00501     main = sys.modules['__main__']
00502     if not hasattr(object, '__name__'):
00503         return None
00504     if hasattr(main, object.__name__):
00505         mainobject = getattr(main, object.__name__)
00506         if mainobject is object:
00507             return main
00508     # Check builtins
00509     builtin = sys.modules['builtins']
00510     if hasattr(builtin, object.__name__):
00511         builtinobject = getattr(builtin, object.__name__)
00512         if builtinobject is object:
00513             return builtin

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getmoduleinfo (   path)
Get the module name, suffix, mode, and module type for a given file.

Definition at line 421 of file inspect.py.

00421 
00422 def getmoduleinfo(path):
00423     """Get the module name, suffix, mode, and module type for a given file."""
00424     filename = os.path.basename(path)
00425     suffixes = [(-len(suffix), suffix, mode, mtype)
00426                     for suffix, mode, mtype in imp.get_suffixes()]
00427     suffixes.sort() # try longest suffixes first, in case they overlap
00428     for neglen, suffix, mode, mtype in suffixes:
00429         if filename[neglen:] == suffix:
00430             return ModuleInfo(filename[:neglen], suffix, mode, mtype)

Here is the caller graph for this function:

def inspect.getmodulename (   path)
Return the module name for a given file, or None.

Definition at line 431 of file inspect.py.

00431 
00432 def getmodulename(path):
00433     """Return the module name for a given file, or None."""
00434     info = getmoduleinfo(path)
00435     if info: return info[0]

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getmro (   cls)

Definition at line 342 of file inspect.py.

00342 
00343 def getmro(cls):
00344     "Return tuple of base classes (including cls) in method resolution order."
00345     return cls.__mro__
00346 
# -------------------------------------------------- source code extraction

Here is the caller graph for this function:

def inspect.getouterframes (   frame,
  context = 1 
)
Get a list of records for a frame and all higher (calling) frames.

Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context.

Definition at line 1034 of file inspect.py.

01034 
01035 def getouterframes(frame, context=1):
01036     """Get a list of records for a frame and all higher (calling) frames.
01037 
01038     Each record contains a frame object, filename, line number, function
01039     name, a list of lines of context, and index within the context."""
01040     framelist = []
01041     while frame:
01042         framelist.append((frame,) + getframeinfo(frame, context))
01043         frame = frame.f_back
01044     return framelist

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getsource (   object)
Return the text of the source code for an object.

The argument may be a module, class, method, function, traceback, frame,
or code object.  The source code is returned as a single string.  An
IOError is raised if the source code cannot be retrieved.

Definition at line 691 of file inspect.py.

00691 
00692 def getsource(object):
00693     """Return the text of the source code for an object.
00694 
00695     The argument may be a module, class, method, function, traceback, frame,
00696     or code object.  The source code is returned as a single string.  An
00697     IOError is raised if the source code cannot be retrieved."""
00698     lines, lnum = getsourcelines(object)
00699     return ''.join(lines)
00700 
# --------------------------------------------------- class tree extraction

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getsourcefile (   object)
Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.

Definition at line 436 of file inspect.py.

00436 
00437 def getsourcefile(object):
00438     """Return the filename that can be used to locate an object's source.
00439     Return None if no way can be identified to get the source.
00440     """
00441     filename = getfile(object)
00442     if filename[-4:].lower() in ('.pyc', '.pyo'):
00443         filename = filename[:-4] + '.py'
00444     for suffix, mode, kind in imp.get_suffixes():
00445         if 'b' in mode and filename[-len(suffix):].lower() == suffix:
00446             # Looks like a binary file.  We want to only return a text file.
00447             return None
00448     if os.path.exists(filename):
00449         return filename
00450     # only return a non-existent filename if the module has a PEP 302 loader
00451     if hasattr(getmodule(object, filename), '__loader__'):
00452         return filename
00453     # or it is in the linecache
00454     if filename in linecache.cache:
00455         return filename

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.getsourcelines (   object)
Return a list of source lines and starting line number for an object.

The argument may be a module, class, method, function, traceback, frame,
or code object.  The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found.  An IOError is
raised if the source code cannot be retrieved.

Definition at line 678 of file inspect.py.

00678 
00679 def getsourcelines(object):
00680     """Return a list of source lines and starting line number for an object.
00681 
00682     The argument may be a module, class, method, function, traceback, frame,
00683     or code object.  The source code is returned as a list of the lines
00684     corresponding to the object and the line number indicates where in the
00685     original source file the first line of code was found.  An IOError is
00686     raised if the source code cannot be retrieved."""
00687     lines, lnum = findsource(object)
00688 
00689     if ismodule(object): return lines, 0
00690     else: return getblock(lines[lnum:]), lnum + 1

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.indentsize (   line)
Return the indent size, in spaces, at the start of a line of text.

Definition at line 347 of file inspect.py.

00347 
00348 def indentsize(line):
00349     """Return the indent size, in spaces, at the start of a line of text."""
00350     expline = line.expandtabs()
00351     return len(expline) - len(expline.lstrip())

Here is the caller graph for this function:

def inspect.isabstract (   object)
Return true if the object is an abstract base class (ABC).

Definition at line 250 of file inspect.py.

00250 
00251 def isabstract(object):
00252     """Return true if the object is an abstract base class (ABC)."""
00253     return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)

Here is the caller graph for this function:

def inspect.isbuiltin (   object)
Return true if the object is a built-in function or method.

Built-in functions and methods provide these attributes:
    __doc__         documentation string
    __name__        original name of this function or method
    __self__        instance to which a method is bound, or None

Definition at line 234 of file inspect.py.

00234 
00235 def isbuiltin(object):
00236     """Return true if the object is a built-in function or method.
00237 
00238     Built-in functions and methods provide these attributes:
00239         __doc__         documentation string
00240         __name__        original name of this function or method
00241         __self__        instance to which a method is bound, or None"""
00242     return isinstance(object, types.BuiltinFunctionType)

Here is the caller graph for this function:

def inspect.isclass (   object)
Return true if the object is a class.

Class objects provide these attributes:
    __doc__         documentation string
    __module__      name of module in which this class was defined

Definition at line 71 of file inspect.py.

00071 
00072 def isclass(object):
00073     """Return true if the object is a class.
00074 
00075     Class objects provide these attributes:
00076         __doc__         documentation string
00077         __module__      name of module in which this class was defined"""
00078     return isinstance(object, type)

Here is the caller graph for this function:

def inspect.iscode (   object)
Return true if the object is a code object.

Code objects provide these attributes:
    co_argcount     number of arguments (not including * or ** args)
    co_code         string of raw compiled bytecode
    co_consts       tuple of constants used in the bytecode
    co_filename     name of file in which this code object was created
    co_firstlineno  number of first line in Python source code
    co_flags        bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
    co_lnotab       encoded mapping of line numbers to bytecode indices
    co_name         name with which this code object was defined
    co_names        tuple of names of local variables
    co_nlocals      number of local variables
    co_stacksize    virtual machine stack space required
    co_varnames     tuple of names of arguments and local variables

Definition at line 216 of file inspect.py.

00216 
00217 def iscode(object):
00218     """Return true if the object is a code object.
00219 
00220     Code objects provide these attributes:
00221         co_argcount     number of arguments (not including * or ** args)
00222         co_code         string of raw compiled bytecode
00223         co_consts       tuple of constants used in the bytecode
00224         co_filename     name of file in which this code object was created
00225         co_firstlineno  number of first line in Python source code
00226         co_flags        bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
00227         co_lnotab       encoded mapping of line numbers to bytecode indices
00228         co_name         name with which this code object was defined
00229         co_names        tuple of names of local variables
00230         co_nlocals      number of local variables
00231         co_stacksize    virtual machine stack space required
00232         co_varnames     tuple of names of arguments and local variables"""
00233     return isinstance(object, types.CodeType)

Here is the caller graph for this function:

def inspect.isdatadescriptor (   object)
Return true if the object is a data descriptor.

Data descriptors have both a __get__ and a __set__ attribute.  Examples are
properties (defined in Python) and getsets and members (defined in C).
Typically, data descriptors will also have __name__ and __doc__ attributes
(properties, getsets, and members have both of these attributes), but this
is not guaranteed.

Definition at line 109 of file inspect.py.

00109 
00110 def isdatadescriptor(object):
00111     """Return true if the object is a data descriptor.
00112 
00113     Data descriptors have both a __get__ and a __set__ attribute.  Examples are
00114     properties (defined in Python) and getsets and members (defined in C).
00115     Typically, data descriptors will also have __name__ and __doc__ attributes
00116     (properties, getsets, and members have both of these attributes), but this
00117     is not guaranteed."""
00118     return (hasattr(object, "__set__") and hasattr(object, "__get__"))

Here is the caller graph for this function:

def inspect.isframe (   object)
Return true if the object is a frame object.

Frame objects provide these attributes:
    f_back          next outer frame object (this frame's caller)
    f_builtins      built-in namespace seen by this frame
    f_code          code object being executed in this frame
    f_globals       global namespace seen by this frame
    f_lasti         index of last attempted instruction in bytecode
    f_lineno        current line number in Python source code
    f_locals        local namespace seen by this frame
    f_trace         tracing function for this frame, or None

Definition at line 202 of file inspect.py.

00202 
00203 def isframe(object):
00204     """Return true if the object is a frame object.
00205 
00206     Frame objects provide these attributes:
00207         f_back          next outer frame object (this frame's caller)
00208         f_builtins      built-in namespace seen by this frame
00209         f_code          code object being executed in this frame
00210         f_globals       global namespace seen by this frame
00211         f_lasti         index of last attempted instruction in bytecode
00212         f_lineno        current line number in Python source code
00213         f_locals        local namespace seen by this frame
00214         f_trace         tracing function for this frame, or None"""
00215     return isinstance(object, types.FrameType)

Here is the caller graph for this function:

def inspect.isfunction (   object)
Return true if the object is a user-defined function.

Function objects provide these attributes:
    __doc__         documentation string
    __name__        name with which this function was defined
    __code__        code object containing compiled function bytecode
    __defaults__    tuple of any default values for arguments
    __globals__     global namespace in which this function was defined
    __annotations__ dict of parameter annotations
    __kwdefaults__  dict of keyword only parameters with defaults

Definition at line 153 of file inspect.py.

00153 
00154 def isfunction(object):
00155     """Return true if the object is a user-defined function.
00156 
00157     Function objects provide these attributes:
00158         __doc__         documentation string
00159         __name__        name with which this function was defined
00160         __code__        code object containing compiled function bytecode
00161         __defaults__    tuple of any default values for arguments
00162         __globals__     global namespace in which this function was defined
00163         __annotations__ dict of parameter annotations
00164         __kwdefaults__  dict of keyword only parameters with defaults"""
00165     return isinstance(object, types.FunctionType)

Here is the caller graph for this function:

def inspect.isgenerator (   object)
Return true if the object is a generator.

Generator objects provide these attributes:
    __iter__        defined to support interation over container
    close           raises a new GeneratorExit exception inside the
                    generator to terminate the iteration
    gi_code         code object
    gi_frame        frame object or possibly None once the generator has
                    been exhausted
    gi_running      set to 1 when generator is executing, 0 otherwise
    next            return the next item from the container
    send            resumes the generator and "sends" a value that becomes
                    the result of the current yield-expression
    throw           used to raise an exception inside the generator

Definition at line 175 of file inspect.py.

00175 
00176 def isgenerator(object):
00177     """Return true if the object is a generator.
00178 
00179     Generator objects provide these attributes:
00180         __iter__        defined to support interation over container
00181         close           raises a new GeneratorExit exception inside the
00182                         generator to terminate the iteration
00183         gi_code         code object
00184         gi_frame        frame object or possibly None once the generator has
00185                         been exhausted
00186         gi_running      set to 1 when generator is executing, 0 otherwise
00187         next            return the next item from the container
00188         send            resumes the generator and "sends" a value that becomes
00189                         the result of the current yield-expression
00190         throw           used to raise an exception inside the generator"""
00191     return isinstance(object, types.GeneratorType)

def inspect.isgeneratorfunction (   object)
Return true if the object is a user-defined generator function.

Generator function objects provides same attributes as functions.

See help(isfunction) for attributes listing.

Definition at line 166 of file inspect.py.

00166 
00167 def isgeneratorfunction(object):
00168     """Return true if the object is a user-defined generator function.
00169 
00170     Generator function objects provides same attributes as functions.
00171 
00172     See help(isfunction) for attributes listing."""
00173     return bool((isfunction(object) or ismethod(object)) and
00174                 object.__code__.co_flags & CO_GENERATOR)

Here is the call graph for this function:

def inspect.isgetsetdescriptor (   object)
Return true if the object is a getset descriptor.

getset descriptors are specialized descriptors defined in extension
modules.

Definition at line 138 of file inspect.py.

00138 
00139     def isgetsetdescriptor(object):
00140         """Return true if the object is a getset descriptor.
00141 
00142         getset descriptors are specialized descriptors defined in extension
00143         modules."""
00144         return isinstance(object, types.GetSetDescriptorType)
else:

Here is the caller graph for this function:

def inspect.ismemberdescriptor (   object)
Return true if the object is a member descriptor.

Member descriptors are specialized descriptors defined in extension
modules.

Definition at line 121 of file inspect.py.

00121 
00122     def ismemberdescriptor(object):
00123         """Return true if the object is a member descriptor.
00124 
00125         Member descriptors are specialized descriptors defined in extension
00126         modules."""
00127         return isinstance(object, types.MemberDescriptorType)
else:

Here is the caller graph for this function:

def inspect.ismethod (   object)
Return true if the object is an instance method.

Instance method objects provide these attributes:
    __doc__         documentation string
    __name__        name with which this method was defined
    __func__        function object containing implementation of method
    __self__        instance to which this method is bound

Definition at line 79 of file inspect.py.

00079 
00080 def ismethod(object):
00081     """Return true if the object is an instance method.
00082 
00083     Instance method objects provide these attributes:
00084         __doc__         documentation string
00085         __name__        name with which this method was defined
00086         __func__        function object containing implementation of method
00087         __self__        instance to which this method is bound"""
00088     return isinstance(object, types.MethodType)

Here is the caller graph for this function:

def inspect.ismethoddescriptor (   object)
Return true if the object is a method descriptor.

But not if ismethod() or isclass() or isfunction() are true.

This is new in Python 2.2, and, for example, is true of int.__add__.
An object passing this test has a __get__ attribute but not a __set__
attribute, but beyond that the set of attributes varies.  __name__ is
usually sensible, and __doc__ often is.

Methods implemented via descriptors that also pass one of the other
tests return false from the ismethoddescriptor() test, simply because
the other tests promise more -- you can, e.g., count on having the
__func__ attribute (etc) when an object passes ismethod().

Definition at line 89 of file inspect.py.

00089 
00090 def ismethoddescriptor(object):
00091     """Return true if the object is a method descriptor.
00092 
00093     But not if ismethod() or isclass() or isfunction() are true.
00094 
00095     This is new in Python 2.2, and, for example, is true of int.__add__.
00096     An object passing this test has a __get__ attribute but not a __set__
00097     attribute, but beyond that the set of attributes varies.  __name__ is
00098     usually sensible, and __doc__ often is.
00099 
00100     Methods implemented via descriptors that also pass one of the other
00101     tests return false from the ismethoddescriptor() test, simply because
00102     the other tests promise more -- you can, e.g., count on having the
00103     __func__ attribute (etc) when an object passes ismethod()."""
00104     return (hasattr(object, "__get__")
00105             and not hasattr(object, "__set__") # else it's a data descriptor
00106             and not ismethod(object)           # mutual exclusion
00107             and not isfunction(object)
00108             and not isclass(object))

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.ismodule (   object)
Return true if the object is a module.

Module objects provide these attributes:
    __cached__      pathname to byte compiled file
    __doc__         documentation string
    __file__        filename (missing for built-in modules)

Definition at line 62 of file inspect.py.

00062 
00063 def ismodule(object):
00064     """Return true if the object is a module.
00065 
00066     Module objects provide these attributes:
00067         __cached__      pathname to byte compiled file
00068         __doc__         documentation string
00069         __file__        filename (missing for built-in modules)"""
00070     return isinstance(object, types.ModuleType)

Here is the caller graph for this function:

def inspect.isroutine (   object)
Return true if the object is any kind of function or method.

Definition at line 243 of file inspect.py.

00243 
00244 def isroutine(object):
00245     """Return true if the object is any kind of function or method."""
00246     return (isbuiltin(object)
00247             or isfunction(object)
00248             or ismethod(object)
00249             or ismethoddescriptor(object))

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.istraceback (   object)
Return true if the object is a traceback.

Traceback objects provide these attributes:
    tb_frame        frame object at this level
    tb_lasti        index of last attempted instruction in bytecode
    tb_lineno       current line number in Python source code
    tb_next         next inner traceback object (called by this level)

Definition at line 192 of file inspect.py.

00192 
00193 def istraceback(object):
00194     """Return true if the object is a traceback.
00195 
00196     Traceback objects provide these attributes:
00197         tb_frame        frame object at this level
00198         tb_lasti        index of last attempted instruction in bytecode
00199         tb_lineno       current line number in Python source code
00200         tb_next         next inner traceback object (called by this level)"""
00201     return isinstance(object, types.TracebackType)

Here is the caller graph for this function:

def inspect.stack (   context = 1)
Return a list of records for the stack above the caller's frame.

Definition at line 1060 of file inspect.py.

01060 
01061 def stack(context=1):
01062     """Return a list of records for the stack above the caller's frame."""
01063     return getouterframes(sys._getframe(1), context)

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.trace (   context = 1)
Return a list of records for the stack below the current exception.

Definition at line 1064 of file inspect.py.

01064 
01065 def trace(context=1):
01066     """Return a list of records for the stack below the current exception."""
01067     return getinnerframes(sys.exc_info()[2], context)
01068 
01069 
01070 # ------------------------------------------------ static version of getattr

Here is the call graph for this function:

Here is the caller graph for this function:

def inspect.walktree (   classes,
  children,
  parent 
)
Recursive helper function for getclasstree().

Definition at line 701 of file inspect.py.

00701 
00702 def walktree(classes, children, parent):
00703     """Recursive helper function for getclasstree()."""
00704     results = []
00705     classes.sort(key=attrgetter('__module__', '__name__'))
00706     for c in classes:
00707         results.append((c, c.__bases__))
00708         if c in children:
00709             results.append(walktree(children[c], children, c))
00710     return results

Here is the caller graph for this function:


Variable Documentation

string inspect.__author__ = 'Ka-Ping Yee <ping@lfw.org>'

Definition at line 29 of file inspect.py.

string inspect.__date__ = '1 Jan 2001'

Definition at line 30 of file inspect.py.

Definition at line 466 of file inspect.py.

Definition at line 1071 of file inspect.py.

tuple inspect.ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')

Definition at line 826 of file inspect.py.

tuple inspect.ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')

Definition at line 777 of file inspect.py.

tuple inspect.Arguments = namedtuple('Arguments', 'args, varargs, varkw')

Definition at line 737 of file inspect.py.

tuple inspect.Attribute = namedtuple('Attribute', 'name kind defining_class object')

Definition at line 268 of file inspect.py.

Initial value:
00001 namedtuple('FullArgSpec',
00002     'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')

Definition at line 800 of file inspect.py.

Definition at line 1161 of file inspect.py.

Definition at line 1158 of file inspect.py.

Definition at line 1159 of file inspect.py.

Definition at line 1160 of file inspect.py.

Definition at line 54 of file inspect.py.

tuple inspect.ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')

Definition at line 419 of file inspect.py.

Definition at line 465 of file inspect.py.

Definition at line 59 of file inspect.py.

tuple inspect.Traceback = namedtuple('Traceback', 'filename lineno function code_context index')

Definition at line 994 of file inspect.py.