[pypy-svn] r28995 - pypy/dist/pypy/module/__builtin__

arigo at codespeak.net arigo at codespeak.net
Tue Jun 20 15:11:44 CEST 2006


Author: arigo
Date: Tue Jun 20 15:11:42 2006
New Revision: 28995

Modified:
   pypy/dist/pypy/module/__builtin__/__init__.py
   pypy/dist/pypy/module/__builtin__/app_descriptor.py
   pypy/dist/pypy/module/__builtin__/app_functional.py
   pypy/dist/pypy/module/__builtin__/app_inspect.py
   pypy/dist/pypy/module/__builtin__/app_io.py
   pypy/dist/pypy/module/__builtin__/app_misc.py
   pypy/dist/pypy/module/__builtin__/compiling.py
   pypy/dist/pypy/module/__builtin__/functional.py
   pypy/dist/pypy/module/__builtin__/operation.py
   pypy/dist/pypy/module/__builtin__/special.py
Log:
Added docstrings to __builtin__ functions.


Modified: pypy/dist/pypy/module/__builtin__/__init__.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/__init__.py	(original)
+++ pypy/dist/pypy/module/__builtin__/__init__.py	Tue Jun 20 15:11:42 2006
@@ -64,8 +64,6 @@
 
     interpleveldefs = {
         # constants
-        '__name__'      : '(space.wrap("__builtin__"))', 
-        '__doc__'       : '(space.wrap("PyPy builtin module"))', 
         'None'          : '(space.w_None)',
         'False'         : '(space.w_False)',
         'True'          : '(space.w_True)',
@@ -152,4 +150,4 @@
                 space.call_function(w_install)
                 # xxx hide the installer
                 space.delitem(self.w_dict, space.wrap(name))
-                del self.loaders[name]
\ No newline at end of file
+                del self.loaders[name]

Modified: pypy/dist/pypy/module/__builtin__/app_descriptor.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/app_descriptor.py	(original)
+++ pypy/dist/pypy/module/__builtin__/app_descriptor.py	Tue Jun 20 15:11:42 2006
@@ -9,6 +9,19 @@
 # XXX there is an interp-level pypy.interpreter.function.StaticMethod
 # XXX because __new__ needs to be a StaticMethod early.
 class staticmethod(object):
+    """staticmethod(function) -> static method
+
+Convert a function to be a static method.
+
+A static method does not receive an implicit first argument.
+To declare a static method, use this idiom:
+
+     class C:
+         def f(arg1, arg2, ...): ...
+         f = staticmethod(f)
+
+It can be called either on the class (e.g. C.f()) or on an instance
+(e.g. C().f()).  The instance is ignored except for its class."""
     __slots__ = ['_f']
 
     def __init__(self, f):
@@ -19,6 +32,22 @@
 
 
 class classmethod(object):
+    """classmethod(function) -> class method
+
+Convert a function to be a class method.
+
+A class method receives the class as implicit first argument,
+just like an instance method receives the instance.
+To declare a class method, use this idiom:
+
+  class C:
+      def f(cls, arg1, arg2, ...): ...
+      f = classmethod(f)
+
+It can be called either on the class (e.g. C.f()) or on an instance
+(e.g. C().f()).  The instance is ignored except for its class.
+If a class method is called for a derived class, the derived class
+object is passed as the implied first argument."""
     __slots__ = ['_f']
 
     def __init__(self, f):
@@ -119,6 +148,15 @@
 #     http://www.python.org/2.2.3/descrintro.html
 # it exposes the same special attributes as CPython's.
 class super(object):
+    """super(type) -> unbound super object
+super(type, obj) -> bound super object; requires isinstance(obj, type)
+super(type, type2) -> bound super object; requires issubclass(type2, type)
+
+Typical use to call a cooperative superclass method:
+
+class C(B):
+    def meth(self, arg):
+        super(C, self).meth(arg)"""
     __slots__ = ['__thisclass__', '__self__', '__self_class__']
     def __init__(self, typ, obj=None):
         if obj is None:

Modified: pypy/dist/pypy/module/__builtin__/app_functional.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/app_functional.py	(original)
+++ pypy/dist/pypy/module/__builtin__/app_functional.py	Tue Jun 20 15:11:42 2006
@@ -5,6 +5,10 @@
 from __future__ import generators
 
 def sum(sequence, total=0):
+    """sum(sequence, start=0) -> value
+
+Returns the sum of a sequence of numbers (NOT strings) plus the value
+of parameter 'start'.  When the sequence is empty, returns start."""
     # must forbid "summing" strings, per specs of built-in 'sum'
     if isinstance(total, str): raise TypeError
     for item in sequence:
@@ -200,7 +204,8 @@
 # operator.__lt__  Perhaps later when we have operator.
 
 def min(*arr):
-    """return the smallest number in a list"""
+    """return the smallest number in a list,
+    or its smallest argument if more than one is given."""
 
     if not arr:
         raise TypeError, 'min() takes at least one argument'
@@ -220,7 +225,8 @@
     return min
 
 def max(*arr):
-    """return the largest number in a list"""
+    """return the largest number in a list,
+    or its largest argument if more than one is given."""
 
     if not arr:
         raise TypeError, 'max() takes at least one argument'
@@ -240,18 +246,25 @@
     return max
 
 class enumerate(object):
+    """enumerate(iterable) -> iterator for (index, value) of iterable.
+
+Return an enumerate object.  iterable must be an other object that supports
+iteration.  The enumerate object yields pairs containing a count (from
+zero) and a value yielded by the iterable argument.  enumerate is useful
+for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."""
+
     def __init__(self, collection):
         self._iter = iter(collection)
         self._index = 0
     
     def next(self):
         try:
-            result = self._index, self._iter.next()
+            next = self._iter.next
         except AttributeError:
             # CPython raises a TypeError when next() is not defined
-            raise TypeError('%s has no next() method' % \
-                            (self._iter))
-
+            raise TypeError('%s object has no next() method' %
+                            (type(self._iter).__name__,))
+        result = self._index, next()
         self._index += 1
         return result
     
@@ -261,18 +274,14 @@
 # ____________________________________________________________
 
 def all( it ):
-    """
-    Implementation of the all() builtin function from 2.5.
-    """
+    "Return True if bool(x) is True for all values x in the given iterable."
     for i in it:
         if not i:
             return False
     return True
     
 def any( it ):
-    """
-    Implementation of the all() builtin function from 2.5.
-    """
+    "Return True if bool(x) is True for any value x in the given iterable."
     for i in it:
         if i:
             return True
@@ -289,6 +298,12 @@
     return n 
     
 class xrange(object):
+    """xrange([start,] stop[, step]) -> xrange object
+
+Like range(), but instead of returning a list, returns an object that
+generates the numbers in the range on demand.  For looping, this is
+more memory efficient."""
+
     def __init__(self, start, stop=None, step=1):
         if not isinstance(start, (int, long, float)):
             raise TypeError('an integer is required')
@@ -383,10 +398,7 @@
     return sorted_lst
 
 def reversed(sequence):
-    """reversed(sequence) -> reverse iterator over values of the sequence
-
-    Return a reverse iterator
-    """
+    "reversed(sequence) -> reverse iterator over values of the sequence"
     if hasattr(sequence, '__reversed__'):
         return sequence.__reversed__()
     if not hasattr(sequence, '__getitem__'):

Modified: pypy/dist/pypy/module/__builtin__/app_inspect.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/app_inspect.py	(original)
+++ pypy/dist/pypy/module/__builtin__/app_inspect.py	Tue Jun 20 15:11:42 2006
@@ -6,9 +6,12 @@
 import sys
 
 def globals():
+    "Return the dictionary containing the current scope's global variables."
     return sys._getframe(0).f_globals
 
 def locals():
+    """Return a dictionary containing the current scope's local variables.
+Note that this may be the real dictionary of local variables, or a copy."""
     return sys._getframe(0).f_locals
 
 def _caller_locals(): 
@@ -41,10 +44,16 @@
         return _recursive_issubclass(cls, klass_or_tuple)
 
 def issubclass(cls, klass_or_tuple):
+    """Check whether a class 'cls' is a subclass (i.e., a derived class) of
+another class.  When using a tuple as the second argument, check whether
+'cls' is a subclass of any of the classes listed in the tuple."""
     import sys
     return _issubclass(cls, klass_or_tuple, True, sys.getrecursionlimit())
 
 def isinstance(obj, klass_or_tuple):
+    """Check whether an object is an instance of a class (or of a subclass
+thereof).  When using a tuple as the second argument, check whether 'obj'
+is an instance of any of the classes listed in the tuple."""
     if issubclass(type(obj), klass_or_tuple):
         return True
     try:
@@ -58,7 +67,7 @@
 
 
 def vars(*obj):
-    """return a dictionary of all the attributes currently bound in obj.  If
+    """Return a dictionary of all the attributes currently bound in obj.  If
     called with no argument, return the variables bound in local scope."""
 
     if len(obj) == 0:
@@ -71,9 +80,10 @@
         except AttributeError:
             raise TypeError, "vars() argument must have __dict__ attribute"
 
-def hasattr(ob, attr):
+def hasattr(obj, attr):
+    """Check whether the object has an attribute with the given name."""
     try:
-        getattr(ob, attr)
+        getattr(obj, attr)
         return True
     except AttributeError:
         return False

Modified: pypy/dist/pypy/module/__builtin__/app_io.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/app_io.py	(original)
+++ pypy/dist/pypy/module/__builtin__/app_io.py	Tue Jun 20 15:11:42 2006
@@ -6,6 +6,11 @@
 import sys
 
 def execfile(filename, glob=None, loc=None):
+    """execfile(filename[, globals[, locals]])
+
+Read and execute a Python script from a file.
+The globals and locals are dictionaries, defaulting to the current
+globals and locals.  If only globals is given, locals defaults to it."""
     if glob is None:
         # Warning this is at hidden_applevel
         glob = globals()
@@ -23,6 +28,12 @@
     exec co in glob, loc
 
 def raw_input(prompt=None):
+    """raw_input([prompt]) -> string
+
+Read a string from standard input.  The trailing newline is stripped.
+If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
+On Unix, GNU readline is used if enabled.  The prompt string, if given,
+is printed without a trailing newline before reading."""
     try:
         sys.stdin
     except AttributeError:
@@ -47,4 +58,5 @@
     return line
 
 def input(prompt=None):
+    """Equivalent to eval(raw_input(prompt))."""
     return eval(raw_input(prompt))

Modified: pypy/dist/pypy/module/__builtin__/app_misc.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/app_misc.py	(original)
+++ pypy/dist/pypy/module/__builtin__/app_misc.py	Tue Jun 20 15:11:42 2006
@@ -40,6 +40,8 @@
      #no hooks match - do normal import
 
 def reload(module):
+    """Reload the module.
+    The module must have been successfully imported before."""
     import imp, sys, errno
 
     if type(module) not in (type(imp), type(errno)):

Modified: pypy/dist/pypy/module/__builtin__/compiling.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/compiling.py	(original)
+++ pypy/dist/pypy/module/__builtin__/compiling.py	Tue Jun 20 15:11:42 2006
@@ -8,6 +8,18 @@
 from pypy.interpreter.gateway import NoneNotWrapped
 
 def compile(space, w_source, filename, mode, flags=0, dont_inherit=0):
+    """Compile the source string (a Python module, statement or expression)
+into a code object that can be executed by the exec statement or eval().
+The filename will be used for run-time error messages.
+The mode must be 'exec' to compile a module, 'single' to compile a
+single (interactive) statement, or 'eval' to compile an expression.
+The flags argument, if present, controls which future statements influence
+the compilation of the code.
+The dont_inherit argument, if non-zero, stops the compilation inheriting
+the effects of any future statements in effect in the code calling
+compile; if absent or zero these statements do influence the compilation,
+in addition to any features explicitly specified.
+"""
     if space.is_true(space.isinstance(w_source, space.w_unicode)):
         # hack: encode the unicode string as UTF-8 and attach
         # a BOM at the start
@@ -38,6 +50,12 @@
 
 
 def eval(space, w_code, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped):
+    """Evaluate the source in the context of globals and locals.
+The source may be a string representing a Python expression
+or a code object as returned by compile().  The globals and locals
+are dictionaries, defaulting to the current current globals and locals.
+If only globals is given, locals defaults to it.
+"""
     w = space.wrap
 
     if (space.is_true(space.isinstance(w_code, space.w_str)) or

Modified: pypy/dist/pypy/module/__builtin__/functional.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/functional.py	(original)
+++ pypy/dist/pypy/module/__builtin__/functional.py	Tue Jun 20 15:11:42 2006
@@ -64,9 +64,9 @@
     return n
 
 def range(space, w_x, w_y=None, w_step=1):
-    """ returns a list of integers in arithmetic position from start (defaults
-        to zero) to stop - 1 by step (defaults to 1).  Use a negative step to
-        get a list in decending order."""
+    """Return a list of integers in arithmetic position from start (defaults
+to zero) to stop - 1 by step (defaults to 1).  Use a negative step to
+get a list in decending order."""
 
     try:
         # save duplication by redirecting every error to applevel

Modified: pypy/dist/pypy/module/__builtin__/operation.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/operation.py	(original)
+++ pypy/dist/pypy/module/__builtin__/operation.py	Tue Jun 20 15:11:42 2006
@@ -12,10 +12,12 @@
     return space.abs(w_val)
 
 def chr(space, w_ascii):
+    "Return a string of one character with the given ascii code."
     w_character = space.newstring([w_ascii])
     return w_character
 
 def unichr(space, w_code):
+    "Return a Unicode string of one character with the given ordinal."
     return space.newunicode([space.int_w(w_code)])
 
 def len(space, w_obj):
@@ -23,10 +25,14 @@
     return space.len(w_obj)
 
 def delattr(space, w_object, w_name):
+    """Delete a named attribute on an object.
+delattr(x, 'y') is equivalent to ``del x.y''."""
     space.delattr(w_object, w_name)
     return space.w_None
 
 def getattr(space, w_object, w_name, w_defvalue=NoneNotWrapped):
+    """Get a named attribute from an object.
+getattr(x, 'y') is equivalent to ``x.y''."""
     if space.is_true(space.isinstance(w_name, space.w_unicode)): # xxx collect this logic somewhere
         w_name = space.call_method(w_name, 'encode')
     try:
@@ -38,16 +44,22 @@
         raise
 
 def hash(space, w_object):
+    """Return a hash value for the object.  Two objects which compare as
+equal have the same hash value.  It is possible, but unlikely, for
+two un-equal objects to have the same hash value."""
     return space.hash(w_object)
 
 def oct(space, w_val):
+    """Return the octal representation of an integer."""
     # XXX does this need to be a space operation?
     return space.oct(w_val)
 
 def hex(space, w_val):
+    """Return the hexadecimal representation of an integer."""
     return space.hex(w_val)
 
 def id(space, w_object):
+    "Return the identity of an object: id(x) == id(y) if and only if x is y."
     return space.id(w_object)
 
 def cmp(space, w_x, w_y):
@@ -57,12 +69,13 @@
 def coerce(space, w_x, w_y):
     """coerce(x, y) -> (x1, y1)
 
-    Return a tuple consisting of the two numeric arguments converted to
-    a common type, using the same rules as used by arithmetic operations.
-    If coercion is not possible, raise TypeError."""
+Return a tuple consisting of the two numeric arguments converted to
+a common type, using the same rules as used by arithmetic operations.
+If coercion is not possible, raise TypeError."""
     return space.coerce(w_x, w_y)
 
 def divmod(space, w_x, w_y):
+    """Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x."""
     return space.divmod(w_x, w_y)
 
 # semi-private: works only for new-style classes.
@@ -77,8 +90,8 @@
 def round(space, number, ndigits=0):
     """round(number[, ndigits]) -> floating point number
 
-    Round a number to a given precision in decimal digits (default 0 digits).
-    This always returns a floating point number.  Precision may be negative."""
+Round a number to a given precision in decimal digits (default 0 digits).
+This always returns a floating point number.  Precision may be negative."""
     # Algortithm copied directly from CPython
     f = 1.0
     if ndigits < 0:
@@ -125,6 +138,11 @@
 ''', filename=__file__).interphook("iter_sentinel")
 
 def iter(space, w_collection_or_callable, w_sentinel=NoneNotWrapped):
+    """iter(collection) -> iterator over the elements of the collection.
+
+iter(callable, sentinel) -> iterator calling callable() until it returns
+                            the sentinal.
+"""
     if w_sentinel is None:
         return space.iter(w_collection_or_callable) 
         # XXX it seems that CPython checks the following 
@@ -148,22 +166,36 @@
     return space.newseqiter(w_obj)
 
 def ord(space, w_val):
+    """Return the integer ordinal of a character."""
     return space.ord(w_val)
 
 def pow(space, w_base, w_exponent, w_modulus=None):
+    """With two arguments, equivalent to ``base**exponent''.
+With three arguments, equivalent to ``(base**exponent) % modulus'',
+but much more efficient for large exponents."""
     return space.pow(w_base, w_exponent, w_modulus)
 
 def repr(space, w_object):
+    """Return a canonical string representation of the object.
+For simple object types, eval(repr(object)) == object."""
     return space.repr(w_object)
 
 def setattr(space, w_object, w_name, w_val):
+    """Store a named attribute into an object.
+setattr(x, 'y', z) is equivalent to ``x.y = z''."""
     space.setattr(w_object, w_name, w_val)
     return space.w_None
 
 def intern(space, w_str):
+    """``Intern'' the given string.  This enters the string in the (global)
+table of interned strings whose purpose is to speed up dictionary lookups.
+Return the string itself or the previously interned string object with the
+same value."""
     if space.is_w(space.type(w_str), space.w_str):
         return space.new_interned_w_str(w_str)
-    raise OperationError(space.w_TypeError, space.wrap("intern() argument 1 must be string."))
+    raise OperationError(space.w_TypeError, space.wrap("intern() argument must be string."))
 
 def callable(space, w_object):
+    """Check whether the object appears to be callable (i.e., some kind of
+function).  Note that classes are callable."""
     return space.callable(w_object)

Modified: pypy/dist/pypy/module/__builtin__/special.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/special.py	(original)
+++ pypy/dist/pypy/module/__builtin__/special.py	Tue Jun 20 15:11:42 2006
@@ -30,4 +30,6 @@
 __pdb._annspecialcase_ = 'override:ignore'
 
 def _pdb(space):
+    """Run an interp-level pdb.
+    This is not available in translated versions of PyPy."""
     __pdb()



More information about the Pypy-commit mailing list