Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
inspect Namespace Reference

Data Structures

class  ListReader
 
class  EndOfBlock
 
class  BlockFinder
 

Functions

def ismodule
 
def isclass
 
def ismethod
 
def ismethoddescriptor
 
def isfunction
 
def istraceback
 
def isframe
 
def iscode
 
def isbuiltin
 
def isroutine
 
def getmembers
 
def classify_class_attrs
 
def getmro
 
def indentsize
 
def getdoc
 
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 getargspec
 
def getargvalues
 
def joinseq
 
def strseq
 
def formatargspec
 
def formatargvalues
 
def getframeinfo
 
def getlineno
 
def getouterframes
 
def getinnerframes
 
def currentframe
 
def stack
 
def trace
 

Variables

string __author__ = 'Ka-Ping Yee <ping@lfw.org>'
 
string __date__ = '1 Jan 2001'
 
dictionary modulesbyfile = {}
 

Detailed Description

Get useful information from live Python objects.

This module encapsulates the interface provided by the internal special
attributes (func_*, 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(), 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() - get info about function arguments
    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.classify_class_attrs (   cls)
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 166 of file inspect.py.

References sre_parse.dir, getmro(), ismethod(), and ismethoddescriptor().

167 def classify_class_attrs(cls):
168  """Return list of attribute-descriptor tuples.
169 
170  For each name in dir(cls), the return list contains a 4-tuple
171  with these elements:
172 
173  0. The name (a string).
174 
175  1. The kind of attribute this is, one of these strings:
176  'class method' created via classmethod()
177  'static method' created via staticmethod()
178  'property' created via property()
179  'method' any other flavor of method
180  'data' not a method
181 
182  2. The class which defined this attribute (a class).
183 
184  3. The object as obtained directly from the defining class's
185  __dict__, not via getattr. This is especially important for
186  data attributes: C.data is just a data object, but
187  C.__dict__['data'] may be a data descriptor with additional
188  info, like a __doc__ string.
189  """
190 
191  mro = getmro(cls)
192  names = dir(cls)
193  result = []
194  for name in names:
195  # Get the object associated with the name.
196  # Getting an obj from the __dict__ sometimes reveals more than
197  # using getattr. Static and class methods are dramatic examples.
198  if name in cls.__dict__:
199  obj = cls.__dict__[name]
200  else:
201  obj = getattr(cls, name)
202 
203  # Figure out where it was defined.
204  homecls = getattr(obj, "__objclass__", None)
205  if homecls is None:
206  # search the dicts.
207  for base in mro:
208  if name in base.__dict__:
209  homecls = base
210  break
211 
212  # Get the object again, in order to get it from the defining
213  # __dict__ instead of via getattr (if possible).
214  if homecls is not None and name in homecls.__dict__:
215  obj = homecls.__dict__[name]
216 
217  # Also get the object via getattr.
218  obj_via_getattr = getattr(cls, name)
219 
220  # Classify the object.
221  if isinstance(obj, staticmethod):
222  kind = "static method"
223  elif isinstance(obj, classmethod):
224  kind = "class method"
225  elif isinstance(obj, property):
226  kind = "property"
227  elif (ismethod(obj_via_getattr) or
228  ismethoddescriptor(obj_via_getattr)):
229  kind = "method"
230  else:
231  kind = "data"
232 
233  result.append((name, kind, homecls, obj))
234 
235  return result
236 
# ----------------------------------------------------------- class helpers
def inspect.currentframe ( )
Return the frame object for the caller's stack frame.

Definition at line 764 of file inspect.py.

765 def currentframe():
766  """Return the frame object for the caller's stack frame."""
767  try:
768  raise 'catch me'
769  except:
770  return sys.exc_traceback.tb_frame.f_back
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 377 of file inspect.py.

References getsourcefile(), isclass(), iscode(), isframe(), isfunction(), ismethod(), ismodule(), istraceback(), and aifc.open().

378 def findsource(object):
379  """Return the entire source file and starting line number for an object.
380 
381  The argument may be a module, class, method, function, traceback, frame,
382  or code object. The source code is returned as a list of all the lines
383  in the file and the line number indexes a line in that list. An IOError
384  is raised if the source code cannot be retrieved."""
385  try:
386  file = open(getsourcefile(object))
387  except (TypeError, IOError):
388  raise IOError, 'could not get source code'
389  lines = file.readlines()
390  file.close()
391 
392  if ismodule(object):
393  return lines, 0
394 
395  if isclass(object):
396  name = object.__name__
397  pat = re.compile(r'^\s*class\s*' + name + r'\b')
398  for i in range(len(lines)):
399  if pat.match(lines[i]): return lines, i
400  else: raise IOError, 'could not find class definition'
401 
402  if ismethod(object):
403  object = object.im_func
404  if isfunction(object):
405  object = object.func_code
406  if istraceback(object):
407  object = object.tb_frame
408  if isframe(object):
409  object = object.f_code
410  if iscode(object):
411  if not hasattr(object, 'co_firstlineno'):
412  raise IOError, 'could not find function definition'
413  lnum = object.co_firstlineno - 1
414  pat = re.compile(r'^\s*def\s')
415  while lnum > 0:
416  if pat.match(lines[lnum]): break
417  lnum = lnum - 1
418  return lines, lnum
419  raise IOError, 'could not find code object'
def inspect.formatargspec (   args,
  varargs = None,
  varkw = None,
  defaults = None,
  formatarg = str,
  formatvarargs = lambda name: '*' + name,
  formatvarkw = lambda name: '**' + name,
  formatvalue = lambda value: '=' + repr(value),
  join = joinseq 
)
Format an argument spec from the 4 values returned by getargspec.

The first four arguments are (args, varargs, varkw, defaults).  The
other 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 650 of file inspect.py.

References formatargvalues(), string.join(), and strseq().

651  join=joinseq):
652  """Format an argument spec from the 4 values returned by getargspec.
653 
654  The first four arguments are (args, varargs, varkw, defaults). The
655  other four arguments are the corresponding optional formatting functions
656  that are called to turn names and values into strings. The ninth
657  argument is an optional function to format the sequence of arguments."""
658  specs = []
659  if defaults:
660  firstdefault = len(args) - len(defaults)
661  for i in range(len(args)):
662  spec = strseq(args[i], formatarg, join)
663  if defaults and i >= firstdefault:
664  spec = spec + formatvalue(defaults[i - firstdefault])
665  specs.append(spec)
666  if varargs:
667  specs.append(formatvarargs(varargs))
668  if varkw:
669  specs.append(formatvarkw(varkw))
670  return '(' + string.join(specs, ', ') + ')'
def inspect.formatargvalues (   args,
  varargs,
  varkw,
  locals,
  formatarg = str,
  formatvarargs = lambda name: '*' + name,
  formatvarkw = lambda name: '**' + name,
  formatvalue = lambda value: '=' + repr(value),
  join = joinseq 
)
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 676 of file inspect.py.

References reconvert.convert(), string.join(), and strseq().

677  join=joinseq):
678  """Format an argument spec from the 4 values returned by getargvalues.
679 
680  The first four arguments are (args, varargs, varkw, locals). The
681  next four arguments are the corresponding optional formatting functions
682  that are called to turn names and values into strings. The ninth
683  argument is an optional function to format the sequence of arguments."""
684  def convert(name, locals=locals,
685  formatarg=formatarg, formatvalue=formatvalue):
686  return formatarg(name) + formatvalue(locals[name])
687  specs = []
688  for i in range(len(args)):
689  specs.append(strseq(args[i], convert, join))
690  if varargs:
691  specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
692  if varkw:
693  specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
694  return '(' + string.join(specs, ', ') + ')'
695 
# -------------------------------------------------- stack frame extraction
def inspect.getabsfile (   object)
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 339 of file inspect.py.

References getfile(), and getsourcefile().

340 def getabsfile(object):
341  """Return an absolute path to the source or compiled file for an object.
342 
343  The idea is for each object to have a unique origin, so this routine
344  normalizes the result as much as possible."""
345  return os.path.normcase(
346  os.path.abspath(getsourcefile(object) or getfile(object)))
def inspect.getargs (   co)
Get information about the arguments accepted by a code object.

Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None.

Definition at line 562 of file inspect.py.

References iscode().

563 def getargs(co):
564  """Get information about the arguments accepted by a code object.
565 
566  Three things are returned: (args, varargs, varkw), where 'args' is
567  a list of argument names (possibly containing nested lists), and
568  'varargs' and 'varkw' are the names of the * and ** arguments or None."""
569  if not iscode(co): raise TypeError, 'arg is not a code object'
570 
571  code = co.co_code
572  nargs = co.co_argcount
573  names = co.co_varnames
574  args = list(names[:nargs])
575  step = 0
576 
577  # The following acrobatics are for anonymous (tuple) arguments.
578  for i in range(nargs):
579  if args[i][:1] in ['', '.']:
580  stack, remain, count = [], [], []
581  while step < len(code):
582  op = ord(code[step])
583  step = step + 1
584  if op >= dis.HAVE_ARGUMENT:
585  opname = dis.opname[op]
586  value = ord(code[step]) + ord(code[step+1])*256
587  step = step + 2
588  if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']:
589  remain.append(value)
590  count.append(value)
591  elif opname == 'STORE_FAST':
592  stack.append(names[value])
593  remain[-1] = remain[-1] - 1
594  while remain[-1] == 0:
595  remain.pop()
596  size = count.pop()
597  stack[-size:] = [stack[-size:]]
598  if not remain: break
599  remain[-1] = remain[-1] - 1
600  if not remain: break
601  args[i] = stack[0]
602 
603  varargs = None
604  if co.co_flags & CO_VARARGS:
605  varargs = co.co_varnames[nargs]
606  nargs = nargs + 1
607  varkw = None
608  if co.co_flags & CO_VARKEYWORDS:
609  varkw = co.co_varnames[nargs]
610  return args, varargs, varkw
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 (it may contain nested lists).
'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.

Definition at line 611 of file inspect.py.

References getargs(), and isfunction().

612 def getargspec(func):
613  """Get the names and default values of a function's arguments.
614 
615  A tuple of four things is returned: (args, varargs, varkw, defaults).
616  'args' is a list of the argument names (it may contain nested lists).
617  'varargs' and 'varkw' are the names of the * and ** arguments or None.
618  'defaults' is an n-tuple of the default values of the last n arguments."""
619  if not isfunction(func): raise TypeError, 'arg is not a Python function'
620  args, varargs, varkw = getargs(func.func_code)
621  return args, varargs, varkw, func.func_defaults
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 (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame.

Definition at line 622 of file inspect.py.

References getargs().

623 def getargvalues(frame):
624  """Get information about arguments passed into a particular frame.
625 
626  A tuple of four things is returned: (args, varargs, varkw, locals).
627  'args' is a list of the argument names (it may contain nested lists).
628  'varargs' and 'varkw' are the names of the * and ** arguments or None.
629  'locals' is the locals dictionary of the given frame."""
630  args, varargs, varkw = getargs(frame.f_code)
631  return args, varargs, varkw, frame.f_locals
def inspect.getblock (   lines)
Extract the block of code at the top of the given list of lines.

Definition at line 493 of file inspect.py.

494 def getblock(lines):
495  """Extract the block of code at the top of the given list of lines."""
496  try:
497  tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
498  except EndOfBlock, eob:
499  return lines[:eob.args[0]]
def inspect.getclasstree (   classes,
  unique = 0 
)
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 533 of file inspect.py.

References reconvert.append, and walktree().

534 def getclasstree(classes, unique=0):
535  """Arrange the given list of classes into a hierarchy of nested lists.
536 
537  Where a nested list appears, it contains classes derived from the class
538  whose entry immediately precedes the list. Each entry is a 2-tuple
539  containing a class and a tuple of its base classes. If the 'unique'
540  argument is true, exactly one entry appears in the returned structure
541  for each class in the given list. Otherwise, classes using multiple
542  inheritance and their descendants will appear multiple times."""
543  children = {}
544  roots = []
545  for c in classes:
546  if c.__bases__:
547  for parent in c.__bases__:
548  if not children.has_key(parent):
549  children[parent] = []
550  children[parent].append(c)
551  if unique and parent in classes: break
552  elif c not in roots:
553  roots.append(c)
554  for parent in children.keys():
555  if parent not in classes:
556  roots.append(parent)
557  return walktree(roots, children, None)
558 
559 # ------------------------------------------------ argument list extraction
560 # These constants are from Python's compile.h.
561 CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
def inspect.getcomments (   object)
Get lines of comments immediately preceding an object's source code.

Definition at line 420 of file inspect.py.

References string.expandtabs(), findsource(), indentsize(), ismodule(), string.join(), string.lstrip(), and string.strip().

421 def getcomments(object):
422  """Get lines of comments immediately preceding an object's source code."""
423  try: lines, lnum = findsource(object)
424  except IOError: return None
425 
426  if ismodule(object):
427  # Look for a comment block at the top of the file.
428  start = 0
429  if lines and lines[0][:2] == '#!': start = 1
430  while start < len(lines) and string.strip(lines[start]) in ['', '#']:
431  start = start + 1
432  if start < len(lines) and lines[start][:1] == '#':
433  comments = []
434  end = start
435  while end < len(lines) and lines[end][:1] == '#':
436  comments.append(string.expandtabs(lines[end]))
437  end = end + 1
438  return string.join(comments, '')
439 
440  # Look for a preceding block of comments at the same indentation.
441  elif lnum > 0:
442  indent = indentsize(lines[lnum])
443  end = lnum - 1
444  if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
445  indentsize(lines[end]) == indent:
446  comments = [string.lstrip(string.expandtabs(lines[end]))]
447  if end > 0:
448  end = end - 1
449  comment = string.lstrip(string.expandtabs(lines[end]))
450  while comment[:1] == '#' and indentsize(lines[end]) == indent:
451  comments[:0] = [comment]
452  end = end - 1
453  if end < 0: break
454  comment = string.lstrip(string.expandtabs(lines[end]))
455  while comments and string.strip(comments[0]) == '#':
456  comments[:1] = []
457  while comments and string.strip(comments[-1]) == '#':
458  comments[-1:] = []
459  return string.join(comments, '')
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 260 of file inspect.py.

References string.expandtabs(), string.join(), string.lstrip(), sre_parse.min, and string.split().

261 def getdoc(object):
262  """Get the documentation string for an object.
263 
264  All tabs are expanded to spaces. To clean up docstrings that are
265  indented to line up with blocks of code, any whitespace than can be
266  uniformly removed from the second line onwards is removed."""
267  try:
268  doc = object.__doc__
269  except AttributeError:
270  return None
271  if not isinstance(doc, (str, unicode)):
272  return None
273  try:
274  lines = string.split(string.expandtabs(doc), '\n')
275  except UnicodeError:
276  return None
277  else:
278  margin = None
279  for line in lines[1:]:
280  content = len(string.lstrip(line))
281  if not content: continue
282  indent = len(line) - content
283  if margin is None: margin = indent
284  else: margin = min(margin, indent)
285  if margin is not None:
286  for i in range(1, len(lines)): lines[i] = lines[i][margin:]
287  return string.join(lines, '\n')
def inspect.getfile (   object)
Work out which source or compiled file an object was defined in.

Definition at line 288 of file inspect.py.

References isclass(), iscode(), isframe(), isfunction(), ismethod(), ismodule(), and istraceback().

289 def getfile(object):
290  """Work out which source or compiled file an object was defined in."""
291  if ismodule(object):
292  if hasattr(object, '__file__'):
293  return object.__file__
294  raise TypeError, 'arg is a built-in module'
295  if isclass(object):
296  object = sys.modules.get(object.__module__)
297  if hasattr(object, '__file__'):
298  return object.__file__
299  raise TypeError, 'arg is a built-in class'
300  if ismethod(object):
301  object = object.im_func
302  if isfunction(object):
303  object = object.func_code
304  if istraceback(object):
305  object = object.tb_frame
306  if isframe(object):
307  object = object.f_code
308  if iscode(object):
309  return object.co_filename
310  raise TypeError, 'arg is not a module, class, method, ' \
311  'function, traceback, frame, or code object'
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 696 of file inspect.py.

References findsource(), getlineno(), getsourcefile(), isframe(), istraceback(), sre_parse.max, and sre_parse.min.

697 def getframeinfo(frame, context=1):
698  """Get information about a frame or traceback object.
699 
700  A tuple of five things is returned: the filename, the line number of
701  the current line, the function name, a list of lines of context from
702  the source code, and the index of the current line within that list.
703  The optional second argument specifies the number of lines of context
704  to return, which are centered around the current line."""
705  if istraceback(frame):
706  frame = frame.tb_frame
707  if not isframe(frame):
708  raise TypeError, 'arg is not a frame or traceback object'
709 
710  filename = getsourcefile(frame)
711  lineno = getlineno(frame)
712  if context > 0:
713  start = lineno - 1 - context//2
714  try:
715  lines, lnum = findsource(frame)
716  except IOError:
717  lines = index = None
718  else:
719  start = max(start, 1)
720  start = min(start, len(lines) - context)
721  lines = lines[start:start+context]
722  index = lineno - 1 - start
723  else:
724  lines = index = None
725 
726  return (filename, lineno, frame.f_code.co_name, lines, index)
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 753 of file inspect.py.

References getframeinfo().

754 def getinnerframes(tb, context=1):
755  """Get a list of records for a traceback's frame and all lower frames.
756 
757  Each record contains a frame object, filename, line number, function
758  name, a list of lines of context, and index within the context."""
759  framelist = []
760  while tb:
761  framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
762  tb = tb.tb_next
763  return framelist
def inspect.getlineno (   frame)
Get the line number from a frame object, allowing for optimization.

Definition at line 727 of file inspect.py.

728 def getlineno(frame):
729  """Get the line number from a frame object, allowing for optimization."""
730  # Written by Marc-André Lemburg; revised by Jim Hugunin and Fredrik Lundh.
731  lineno = frame.f_lineno
732  code = frame.f_code
733  if hasattr(code, 'co_lnotab'):
734  table = code.co_lnotab
735  lineno = code.co_firstlineno
736  addr = 0
737  for i in range(0, len(table), 2):
738  addr = addr + ord(table[i])
739  if addr > frame.f_lasti: break
740  lineno = lineno + ord(table[i+1])
741  return 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 155 of file inspect.py.

References sre_parse.dir.

156 def getmembers(object, predicate=None):
157  """Return all members of an object as (name, value) pairs sorted by name.
158  Optionally, only return members that satisfy a given predicate."""
159  results = []
160  for key in dir(object):
161  value = getattr(object, key)
162  if not predicate or predicate(value):
163  results.append((key, value))
164  results.sort()
165  return results
def inspect.getmodule (   object)
Return the module an object was defined in, or None if not found.

Definition at line 349 of file inspect.py.

References getabsfile(), isclass(), and ismodule().

350 def getmodule(object):
351  """Return the module an object was defined in, or None if not found."""
352  if ismodule(object):
353  return object
354  if isclass(object):
355  return sys.modules.get(object.__module__)
356  try:
357  file = getabsfile(object)
358  except TypeError:
359  return None
360  if modulesbyfile.has_key(file):
361  return sys.modules[modulesbyfile[file]]
362  for module in sys.modules.values():
363  if hasattr(module, '__file__'):
364  modulesbyfile[getabsfile(module)] = module.__name__
365  if modulesbyfile.has_key(file):
366  return sys.modules[modulesbyfile[file]]
367  main = sys.modules['__main__']
368  if hasattr(main, object.__name__):
369  mainobject = getattr(main, object.__name__)
370  if mainobject is object:
371  return main
372  builtin = sys.modules['__builtin__']
373  if hasattr(builtin, object.__name__):
374  builtinobject = getattr(builtin, object.__name__)
375  if builtinobject is object:
376  return builtin
def inspect.getmoduleinfo (   path)
Get the module name, suffix, mode, and module type for a given file.

Definition at line 312 of file inspect.py.

313 def getmoduleinfo(path):
314  """Get the module name, suffix, mode, and module type for a given file."""
315  filename = os.path.basename(path)
316  suffixes = map(lambda (suffix, mode, mtype):
317  (-len(suffix), suffix, mode, mtype), imp.get_suffixes())
318  suffixes.sort() # try longest suffixes first, in case they overlap
319  for neglen, suffix, mode, mtype in suffixes:
320  if filename[neglen:] == suffix:
321  return filename[:neglen], suffix, mode, mtype
def inspect.getmodulename (   path)
Return the module name for a given file, or None.

Definition at line 322 of file inspect.py.

References getmoduleinfo().

323 def getmodulename(path):
324  """Return the module name for a given file, or None."""
325  info = getmoduleinfo(path)
326  if info: return info[0]
def inspect.getmro (   cls)

Definition at line 245 of file inspect.py.

References log_faction_ships.tuple.

246 def getmro(cls):
247  "Return tuple of base classes (including cls) in method resolution order."
248  if hasattr(cls, "__mro__"):
249  return cls.__mro__
250  else:
251  result = []
252  _searchbases(cls, result)
253  return tuple(result)
254 
# -------------------------------------------------- source code extraction
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 742 of file inspect.py.

References getframeinfo().

743 def getouterframes(frame, context=1):
744  """Get a list of records for a frame and all higher (calling) frames.
745 
746  Each record contains a frame object, filename, line number, function
747  name, a list of lines of context, and index within the context."""
748  framelist = []
749  while frame:
750  framelist.append((frame,) + getframeinfo(frame, context))
751  frame = frame.f_back
752  return framelist
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 513 of file inspect.py.

References getsourcelines(), and string.join().

514 def getsource(object):
515  """Return the text of the source code for an object.
516 
517  The argument may be a module, class, method, function, traceback, frame,
518  or code object. The source code is returned as a single string. An
519  IOError is raised if the source code cannot be retrieved."""
520  lines, lnum = getsourcelines(object)
521  return string.join(lines, '')
522 
# --------------------------------------------------- class tree extraction
def inspect.getsourcefile (   object)
Return the Python source file an object was defined in, if it exists.

Definition at line 327 of file inspect.py.

References getfile(), and string.lower().

328 def getsourcefile(object):
329  """Return the Python source file an object was defined in, if it exists."""
330  filename = getfile(object)
331  if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
332  filename = filename[:-4] + '.py'
333  for suffix, mode, kind in imp.get_suffixes():
334  if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
335  # Looks like a binary file. We want to only return a text file.
336  return None
337  if os.path.exists(filename):
338  return filename
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 500 of file inspect.py.

References findsource(), getblock(), and ismodule().

501 def getsourcelines(object):
502  """Return a list of source lines and starting line number for an object.
503 
504  The argument may be a module, class, method, function, traceback, frame,
505  or code object. The source code is returned as a list of the lines
506  corresponding to the object and the line number indicates where in the
507  original source file the first line of code was found. An IOError is
508  raised if the source code cannot be retrieved."""
509  lines, lnum = findsource(object)
510 
511  if ismodule(object): return lines, 0
512  else: return getblock(lines[lnum:]), lnum + 1
def inspect.indentsize (   line)
Return the indent size, in spaces, at the start of a line of text.

Definition at line 255 of file inspect.py.

References string.expandtabs(), and string.lstrip().

256 def indentsize(line):
257  """Return the indent size, in spaces, at the start of a line of text."""
258  expline = string.expandtabs(line)
259  return len(expline) - len(string.lstrip(expline))
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 139 of file inspect.py.

140 def isbuiltin(object):
141  """Return true if the object is a built-in function or method.
142 
143  Built-in functions and methods provide these attributes:
144  __doc__ documentation string
145  __name__ original name of this function or method
146  __self__ instance to which a method is bound, or None"""
147  return isinstance(object, types.BuiltinFunctionType)
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 41 of file inspect.py.

41 
42 def isclass(object):
43  """Return true if the object is a class.
44 
45  Class objects provide these attributes:
46  __doc__ documentation string
47  __module__ name of module in which this class was defined"""
48  return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
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 121 of file inspect.py.

122 def iscode(object):
123  """Return true if the object is a code object.
124 
125  Code objects provide these attributes:
126  co_argcount number of arguments (not including * or ** args)
127  co_code string of raw compiled bytecode
128  co_consts tuple of constants used in the bytecode
129  co_filename name of file in which this code object was created
130  co_firstlineno number of first line in Python source code
131  co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
132  co_lnotab encoded mapping of line numbers to bytecode indices
133  co_name name with which this code object was defined
134  co_names tuple of names of local variables
135  co_nlocals number of local variables
136  co_stacksize virtual machine stack space required
137  co_varnames tuple of names of arguments and local variables"""
138  return isinstance(object, types.CodeType)
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_exc_traceback traceback if raised in this frame, or None
    f_exc_type      exception type if raised in this frame, or None
    f_exc_value     exception value if raised in this frame, or None
    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_restricted    0 or 1 if frame is in restricted execution mode
    f_trace         tracing function for this frame, or None

Definition at line 103 of file inspect.py.

104 def isframe(object):
105  """Return true if the object is a frame object.
106 
107  Frame objects provide these attributes:
108  f_back next outer frame object (this frame's caller)
109  f_builtins built-in namespace seen by this frame
110  f_code code object being executed in this frame
111  f_exc_traceback traceback if raised in this frame, or None
112  f_exc_type exception type if raised in this frame, or None
113  f_exc_value exception value if raised in this frame, or None
114  f_globals global namespace seen by this frame
115  f_lasti index of last attempted instruction in bytecode
116  f_lineno current line number in Python source code
117  f_locals local namespace seen by this frame
118  f_restricted 0 or 1 if frame is in restricted execution mode
119  f_trace tracing function for this frame, or None"""
120  return isinstance(object, types.FrameType)
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
    func_code       code object containing compiled function bytecode
    func_defaults   tuple of any default values for arguments
    func_doc        (same as __doc__)
    func_globals    global namespace in which this function was defined
    func_name       (same as __name__)

Definition at line 80 of file inspect.py.

80 
81 def isfunction(object):
82  """Return true if the object is a user-defined function.
83 
84  Function objects provide these attributes:
85  __doc__ documentation string
86  __name__ name with which this function was defined
87  func_code code object containing compiled function bytecode
88  func_defaults tuple of any default values for arguments
89  func_doc (same as __doc__)
90  func_globals global namespace in which this function was defined
91  func_name (same as __name__)"""
92  return isinstance(object, types.FunctionType)
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
    im_class        class object in which this method belongs
    im_func         function object containing implementation of method
    im_self         instance to which this method is bound, or None

Definition at line 49 of file inspect.py.

49 
50 def ismethod(object):
51  """Return true if the object is an instance method.
52 
53  Instance method objects provide these attributes:
54  __doc__ documentation string
55  __name__ name with which this method was defined
56  im_class class object in which this method belongs
57  im_func function object containing implementation of method
58  im_self instance to which this method is bound, or None"""
59  return isinstance(object, types.MethodType)
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
im_func attribute (etc) when an object passes ismethod().

Definition at line 60 of file inspect.py.

References isclass(), isfunction(), and ismethod().

60 
61 def ismethoddescriptor(object):
62  """Return true if the object is a method descriptor.
63 
64  But not if ismethod() or isclass() or isfunction() are true.
65 
66  This is new in Python 2.2, and, for example, is true of int.__add__.
67  An object passing this test has a __get__ attribute but not a __set__
68  attribute, but beyond that the set of attributes varies. __name__ is
69  usually sensible, and __doc__ often is.
70 
71  Methods implemented via descriptors that also pass one of the other
72  tests return false from the ismethoddescriptor() test, simply because
73  the other tests promise more -- you can, e.g., count on having the
74  im_func attribute (etc) when an object passes ismethod()."""
75  return (hasattr(object, "__get__")
76  and not hasattr(object, "__set__") # else it's a data descriptor
77  and not ismethod(object) # mutual exclusion
78  and not isfunction(object)
79  and not isclass(object))
def inspect.ismodule (   object)
Return true if the object is a module.

Module objects provide these attributes:
    __doc__         documentation string
    __file__        filename (missing for built-in modules)

Definition at line 33 of file inspect.py.

33 
34 def ismodule(object):
35  """Return true if the object is a module.
36 
37  Module objects provide these attributes:
38  __doc__ documentation string
39  __file__ filename (missing for built-in modules)"""
40  return isinstance(object, types.ModuleType)
def inspect.isroutine (   object)
Return true if the object is any kind of function or method.

Definition at line 148 of file inspect.py.

References isbuiltin(), isfunction(), ismethod(), and ismethoddescriptor().

149 def isroutine(object):
150  """Return true if the object is any kind of function or method."""
151  return (isbuiltin(object)
152  or isfunction(object)
153  or ismethod(object)
154  or ismethoddescriptor(object))
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 93 of file inspect.py.

93 
94 def istraceback(object):
95  """Return true if the object is a traceback.
96 
97  Traceback objects provide these attributes:
98  tb_frame frame object at this level
99  tb_lasti index of last attempted instruction in bytecode
100  tb_lineno current line number in Python source code
101  tb_next next inner traceback object (called by this level)"""
102  return isinstance(object, types.TracebackType)
def inspect.joinseq (   seq)

Definition at line 632 of file inspect.py.

References string.join().

633 def joinseq(seq):
634  if len(seq) == 1:
635  return '(' + seq[0] + ',)'
636  else:
637  return '(' + string.join(seq, ', ') + ')'
def inspect.stack (   context = 1)
Return a list of records for the stack above the caller's frame.

Definition at line 773 of file inspect.py.

References currentframe(), and getouterframes().

774 def stack(context=1):
775  """Return a list of records for the stack above the caller's frame."""
776  return getouterframes(currentframe().f_back, context)
def inspect.strseq (   object,
  convert,
  join = joinseq 
)
Recursively walk a sequence, stringifying each element.

Definition at line 638 of file inspect.py.

References reconvert.convert(), formatargspec(), and dospath.join().

639 def strseq(object, convert, join=joinseq):
640  """Recursively walk a sequence, stringifying each element."""
641  if type(object) in [types.ListType, types.TupleType]:
642  return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
643  else:
644  return convert(object)
def inspect.trace (   context = 1)
Return a list of records for the stack below the current exception.

Definition at line 777 of file inspect.py.

References getinnerframes().

778 def trace(context=1):
779  """Return a list of records for the stack below the current exception."""
780  return getinnerframes(sys.exc_traceback, context)
def inspect.walktree (   classes,
  children,
  parent 
)
Recursive helper function for getclasstree().

Definition at line 523 of file inspect.py.

References filecmp.cmp().

524 def walktree(classes, children, parent):
525  """Recursive helper function for getclasstree()."""
526  results = []
527  classes.sort(lambda a, b: cmp(a.__name__, b.__name__))
528  for c in classes:
529  results.append((c, c.__bases__))
530  if children.has_key(c):
531  results.append(walktree(children[c], children, c))
532  return results

Variable Documentation

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

Definition at line 27 of file inspect.py.

string __date__ = '1 Jan 2001'

Definition at line 28 of file inspect.py.

dictionary modulesbyfile = {}

Definition at line 347 of file inspect.py.