[Python-checkins] CVS: python/nondist/sandbox/help inspect.py,1.3,1.4 pydoc.py,1.3,1.4 test_inspect.py,1.2,1.3 htmldoc.py,1.6,NONE textdoc.py,1.4,NONE
Ka-Ping Yee
ping@users.sourceforge.net
Mon, 26 Feb 2001 23:41:11 -0800
Update of /cvsroot/python/python/nondist/sandbox/help
In directory usw-pr-cvs1:/tmp/cvs-serv14426
Modified Files:
inspect.py pydoc.py test_inspect.py
Removed Files:
htmldoc.py textdoc.py
Log Message:
pydoc is now a single file.
Handle methods at module toplevel.
Improved formatting.
Added ability to write out files to disk.
Index: inspect.py
===================================================================
RCS file: /cvsroot/python/python/nondist/sandbox/help/inspect.py,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -r1.3 -r1.4
*** inspect.py 2001/01/14 11:58:17 1.3
--- inspect.py 2001/02/27 07:41:09 1.4
***************
*** 7,15 ****
Here are some of the useful functions provided by this module:
getdoc(), getcomments() - get documentation on an object
getclasstree() - arrange classes so as to represent their hierarchy
! getfile(), getsourcefile(), getsource() - find an object's source code
getargspec(), getargvalues() - get info about function arguments
formatargspec(), formatargvalues() - format an argument spec
stack(), trace() - get info about frames on the stack or in a traceback
"""
--- 7,23 ----
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
"""
***************
*** 19,23 ****
__version__ = 'Ka-Ping Yee <ping@lfw.org>, 1 Jan 2001'
! import sys, types, string, dis, imp
# ----------------------------------------------------------- type-checking
--- 27,31 ----
__version__ = 'Ka-Ping Yee <ping@lfw.org>, 1 Jan 2001'
! import sys, types, string, dis, imp, tokenize
# ----------------------------------------------------------- type-checking
***************
*** 125,129 ****
def getmembers(object, predicate=None):
! """Return all members of an object as (key, value) pairs sorted by key.
Optionally, only return members that satisfy a given predicate."""
results = []
--- 133,137 ----
def 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."""
results = []
***************
*** 220,227 ****
def findsource(object):
! """Find the first line of code corresponding to a given module, class,
! method, function, traceback, frame, or code object; return the entire
! contents of the source file and the starting line number. An IOError
! exception is raised if the source code cannot be retrieved."""
try:
file = open(getsourcefile(object))
--- 228,237 ----
def 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."""
try:
file = open(getsourcefile(object))
***************
*** 284,294 ****
indent = indentsize(lines[lnum])
end = lnum - 1
- if string.strip(lines[end]) == '':
- while end >= 0 and string.strip(lines[end]) == '':
- end = end - 1
- else:
- while string.lstrip(lines[end])[:1] != '#' and \
- indentsize(lines[end]) == indent:
- end = end - 1
if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
indentsize(lines[end]) == indent:
--- 294,297 ----
***************
*** 302,309 ****
if end < 0: break
comment = string.lstrip(string.expandtabs(lines[end]))
return string.join(comments, '')
- import tokenize
-
class ListReader:
"""Provide a readline() method to return lines from a list of strings."""
--- 305,314 ----
if end < 0: break
comment = string.lstrip(string.expandtabs(lines[end]))
+ while comments and string.strip(comments[0]) == '#':
+ comments[:1] = []
+ while comments and string.strip(comments[-1]) == '#':
+ comments[-1:] = []
return string.join(comments, '')
class ListReader:
"""Provide a readline() method to return lines from a list of strings."""
***************
*** 347,363 ****
def getsourcelines(object):
! """Try to get the source code corresponding to a module, class, method,
! function, traceback, frame, or code object. Return a list of lines and
! the line number of the first line, or raise an IOError exception if the
! source code cannot be retrieved."""
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
! else: return getblock(lines[lnum:]), lnum
def getsource(object):
! """Try to get the source code corresponding to a module, class, method,
! function, traceback, frame, or code object. Return a string, or raise
! an IOError exception if the source code cannot be retrieved."""
lines, lnum = getsourcelines(object)
return string.join(lines, '')
--- 352,373 ----
def 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."""
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
! else: return getblock(lines[lnum:]), lnum + 1
def 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."""
lines, lnum = getsourcelines(object)
return string.join(lines, '')
***************
*** 376,385 ****
def 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 that multiply
! inherit, and their descendants, will appear multiple times."""
children = {}
roots = []
--- 386,396 ----
def 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."""
children = {}
roots = []
***************
*** 404,407 ****
--- 415,419 ----
def 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
***************
*** 452,455 ****
--- 464,468 ----
def 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).
***************
*** 462,465 ****
--- 475,479 ----
def 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).
***************
*** 468,527 ****
args, varargs, varkw = getargs(frame.f_code)
return args, varargs, varkw, frame.f_locals
! def strseq(object, convert=str):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in [types.ListType, types.TupleType]:
! results = map(lambda o, c=convert: strseq(o, c), object)
! if len(results) == 1:
! return '(' + results[0] + ',)'
! else:
! return '(' + string.join(results, ', ') + ')'
else:
return convert(object)
def formatargspec(args, varargs=None, varkw=None, defaults=None,
! argformat=str, defaultformat=lambda x: '=' + repr(x),
! varargsformat=lambda name: '*' + name,
! varkwformat=lambda name: '**' + name):
! """Format a pretty argument spec from the 4-tuple returned by getargspec.
! The arguments are (args, varargs, varkw, defaults)."""
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i in range(len(args)):
! spec = strseq(args[i], argformat)
if defaults and i >= firstdefault:
! spec = spec + defaultformat(defaults[i - firstdefault])
specs.append(spec)
if varargs:
! specs.append(varargsformat(varargs))
if varkw:
! specs.append(varkwformat(varkw))
return '(' + string.join(specs, ', ') + ')'
def formatargvalues(args, varargs, varkw, locals,
! argformat=str, valueformat=repr,
! varargsformat=lambda name: '*' + name,
! varkwformat=lambda name: '**' + name):
! """Format a pretty argument spec from the 4-tuple returned by getargvalues.
! The arguments are (args, varargs, varkw, locals)."""
def convert(name, locals=locals,
! argformat=argformat, valueformat=valueformat):
! return argformat(name) + '=' + valueformat(locals[name])
specs = []
for i in range(len(args)):
! specs.append(strseq(args[i], convert))
if varargs:
! specs.append(varargsformat(varargs) + '=' +
! valueformat(locals[varargs]))
! if varkw:
! specs.append(varkwformat(varkw) + '=' + valueformat(locals[varkw]))
return '(' + string.join(specs, ', ') + ')'
# -------------------------------------------------- stack frame extraction
! def getframe(frame, context=1):
! """For a given frame or traceback object, return the filename, line
! number, function name, a given number of lines of context from the
! source code, and the index of the line within the lines of context."""
if istraceback(frame):
frame = frame.tb_frame
--- 482,558 ----
args, varargs, varkw = getargs(frame.f_code)
return args, varargs, varkw, frame.f_locals
+
+ def joinseq(seq):
+ if len(seq) == 1:
+ return '(' + seq[0] + ',)'
+ else:
+ return '(' + string.join(seq, ', ') + ')'
! def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in [types.ListType, types.TupleType]:
! return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
else:
return convert(object)
def 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."""
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i in range(len(args)):
! spec = strseq(args[i], formatarg, join)
if defaults and i >= firstdefault:
! spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs:
! specs.append(formatvarargs(varargs))
if varkw:
! specs.append(formatvarkw(varkw))
return '(' + string.join(specs, ', ') + ')'
def 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."""
def convert(name, locals=locals,
! formatarg=formatarg, formatvalue=formatvalue):
! return formatarg(name) + formatvalue(locals[name])
specs = []
for i in range(len(args)):
! specs.append(strseq(args[i], convert, join))
if varargs:
! specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
! if varkw:
! specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
return '(' + string.join(specs, ', ') + ')'
# -------------------------------------------------- stack frame extraction
! def 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."""
if istraceback(frame):
frame = frame.tb_frame
***************
*** 547,567 ****
def 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, the requested amount of context, and index within the context."""
framelist = []
while frame:
! framelist.append((frame,) + getframe(frame, context))
frame = frame.f_back
return framelist
! def getinnerframes(traceback, 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, the requested amount of context, and index within the context."""
! traceback = traceback.tb_next
framelist = []
! while traceback:
! framelist.append((traceback.tb_frame,) + getframe(traceback, context))
! traceback = traceback.tb_next
return framelist
--- 578,600 ----
def 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."""
framelist = []
while frame:
! framelist.append((frame,) + getframeinfo(frame, context))
frame = frame.f_back
return framelist
! def 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."""
! tb = tb.tb_next
framelist = []
! while tb:
! framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
! tb = tb.tb_next
return framelist
Index: pydoc.py
===================================================================
RCS file: /cvsroot/python/python/nondist/sandbox/help/pydoc.py,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -r1.3 -r1.4
*** pydoc.py 2001/01/14 22:18:44 1.3
--- pydoc.py 2001/02/27 07:41:09 1.4
***************
*** 1,10 ****
#!/usr/bin/env python
- """Format Python documentation for interactive use.
-
At the shell command line outside of Python, run "pydoc <name>" to show
documentation on something. <name> may be the name of a Python function,
module, package, or a dotted reference to a class or function within a
! module or module in a package.
Or, at the shell prompt, run "pydoc -k <keyword>" to search for a keyword
[...1209 lines suppressed...]
! print """%s <object> ...
! Show documentation on something.
! <object> may be the name of a Python function, module,
! package, or a dotted reference to a class or function
! within a module or module in a package, or the name of
! a Python source file to import.
!
! %s -k <keyword>
! Search for a keyword in the synopsis lines of all modules.
!
! %s -p <port>
! Start an HTTP server on the given port on the local machine.
!
! %s -w <module> ...
! Write out the HTML documentation for a module to a file.
!
! %s -w <moduledir>
! Write out the HTML documentation for all modules under
! a directory to files in the current directory.
! """ % ((sys.argv[0],) * 5)
Index: test_inspect.py
===================================================================
RCS file: /cvsroot/python/python/nondist/sandbox/help/test_inspect.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -r1.2 -r1.3
*** test_inspect.py 2001/01/15 22:38:43 1.2
--- test_inspect.py 2001/02/27 07:41:09 1.3
***************
*** 52,60 ****
class ParrotDroppings:
pass
!
class FesteringGob(MalodorousPervert, ParrotDroppings):
pass
'''
from test_support import TestFailed, TESTFN
import sys, imp, os, string
--- 52,66 ----
class ParrotDroppings:
pass
!
class FesteringGob(MalodorousPervert, ParrotDroppings):
pass
'''
+ # Functions tested in this suite:
+ # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
+ # isbuiltin, isroutine, getmembers, getdoc, getfile, getmodule,
+ # getsourcefile, getcomments, getsource, getclasstree, getargspec,
+ # getargvalues, formatargspec, formatargvalues, currentframe, stack, trace
+
from test_support import TestFailed, TESTFN
import sys, imp, os, string
***************
*** 97,100 ****
--- 103,108 ----
istest(inspect.ismodule, 'mod')
istest(inspect.istraceback, 'tb')
+ test(inspect.isroutine(mod.spam), 'isroutine(mod.spam)')
+ test(inspect.isroutine([].count), 'isroutine([].count)')
classes = inspect.getmembers(mod, inspect.isclass)
--- htmldoc.py DELETED ---
--- textdoc.py DELETED ---