]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Merged revisions 59703-59773 via svnmerge from
authorChristian Heimes <christian@cheimes.de>
Sun, 6 Jan 2008 16:59:19 +0000 (16:59 +0000)
committerChristian Heimes <christian@cheimes.de>
Sun, 6 Jan 2008 16:59:19 +0000 (16:59 +0000)
svn+ssh://pythondev@svn.python.org/python/trunk

........
  r59704 | christian.heimes | 2008-01-04 04:15:05 +0100 (Fri, 04 Jan 2008) | 1 line

  Moved include "Python.h" in front of other imports to silence a warning.
........
  r59706 | raymond.hettinger | 2008-01-04 04:22:53 +0100 (Fri, 04 Jan 2008) | 10 lines

  Minor fix-ups to named tuples:

  * Make the _replace() method respect subclassing.

  * Using property() to make _fields read-only wasn't a good idea.
    It caused len(Point._fields) to fail.

  * Add note to _cast() about length checking and alternative with the star-operator.
........
  r59707 | jeffrey.yasskin | 2008-01-04 09:01:23 +0100 (Fri, 04 Jan 2008) | 3 lines

  Make math.{floor,ceil}({int,long}) return float again for backwards
  compatibility after r59671 made them return integral types.
........
  r59709 | christian.heimes | 2008-01-04 14:21:07 +0100 (Fri, 04 Jan 2008) | 1 line

  Bug #1713: posixpath.ismount() claims symlink to a mountpoint is a mountpoint.
........
  r59712 | lars.gustaebel | 2008-01-04 15:00:33 +0100 (Fri, 04 Jan 2008) | 5 lines

  Issue #1735: TarFile.extractall() now correctly sets
  directory permissions and times.

  (will backport to 2.5)
........
  r59714 | andrew.kuchling | 2008-01-04 15:47:17 +0100 (Fri, 04 Jan 2008) | 1 line

  Update links to bug/patch tracker
........
  r59716 | christian.heimes | 2008-01-04 16:23:30 +0100 (Fri, 04 Jan 2008) | 1 line

  Added interface to Windows' WSAIoctl and a simple example for a network sniffer.
........
  r59717 | christian.heimes | 2008-01-04 16:29:00 +0100 (Fri, 04 Jan 2008) | 1 line

  And here is the rest of Hirokazu Yamamoto's patch for VS6.0 support. Thanks Hiro!
........
  r59719 | christian.heimes | 2008-01-04 16:34:06 +0100 (Fri, 04 Jan 2008) | 1 line

  Reverted last transaction. It's the wrong branch.
........
  r59721 | christian.heimes | 2008-01-04 16:48:06 +0100 (Fri, 04 Jan 2008) | 1 line

  socket.ioctl is only available on Windows
........
  r59722 | andrew.kuchling | 2008-01-04 19:24:41 +0100 (Fri, 04 Jan 2008) | 1 line

  Fix markup
........
  r59723 | andrew.kuchling | 2008-01-04 19:25:05 +0100 (Fri, 04 Jan 2008) | 1 line

  Fix markup
........
  r59725 | guido.van.rossum | 2008-01-05 01:59:59 +0100 (Sat, 05 Jan 2008) | 3 lines

  Patch #1725 by Mark Dickinson, fixes incorrect conversion of -1e1000
  and adds errors for -0x.
........
  r59726 | guido.van.rossum | 2008-01-05 02:21:57 +0100 (Sat, 05 Jan 2008) | 2 lines

  Patch #1698 by Senthil: allow '@' in username when parsed by urlparse.py.
........
  r59727 | raymond.hettinger | 2008-01-05 02:35:43 +0100 (Sat, 05 Jan 2008) | 1 line

  Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
........
  r59728 | raymond.hettinger | 2008-01-05 03:17:24 +0100 (Sat, 05 Jan 2008) | 1 line

  Add error-checking to namedtuple's _replace() method.
........
  r59730 | fred.drake | 2008-01-05 05:38:38 +0100 (Sat, 05 Jan 2008) | 2 lines

  clean up a comment
........
  r59731 | jeffrey.yasskin | 2008-01-05 09:47:13 +0100 (Sat, 05 Jan 2008) | 11 lines

  Continue rolling back pep-3141 changes that changed behavior from 2.5. This
  round included:
   * Revert round to its 2.6 behavior (half away from 0).
   * Because round, floor, and ceil always return float again, it's no
     longer necessary to have them delegate to __xxx___, so I've ripped
     that out of their implementations and the Real ABC. This also helps
     in implementing types that work in both 2.6 and 3.0: you return int
     from the __xxx__ methods, and let it get enabled by the version
     upgrade.
   * Make pow(-1, .5) raise a ValueError again.
........
  r59736 | andrew.kuchling | 2008-01-05 16:13:49 +0100 (Sat, 05 Jan 2008) | 1 line

  Fix comment typo
........
  r59738 | thomas.heller | 2008-01-05 18:15:44 +0100 (Sat, 05 Jan 2008) | 1 line

  Add myself.
........
  r59739 | georg.brandl | 2008-01-05 18:49:17 +0100 (Sat, 05 Jan 2008) | 2 lines

  Fix C++-style comment.
........
  r59742 | georg.brandl | 2008-01-05 20:28:16 +0100 (Sat, 05 Jan 2008) | 2 lines

  Remove with_statement future imports from 2.6 docs.
........
  r59743 | georg.brandl | 2008-01-05 20:29:45 +0100 (Sat, 05 Jan 2008) | 2 lines

  Simplify index entries; fix #1712.
........
  r59744 | georg.brandl | 2008-01-05 20:44:22 +0100 (Sat, 05 Jan 2008) | 2 lines

  Doc patch #1730 from Robin Stocker; minor corrections mostly to os.rst.
........
  r59749 | georg.brandl | 2008-01-05 21:29:13 +0100 (Sat, 05 Jan 2008) | 2 lines

  Revert socket.rst to unix-eol.
........
  r59750 | georg.brandl | 2008-01-05 21:33:46 +0100 (Sat, 05 Jan 2008) | 2 lines

  Set native svn:eol-style property for text files.
........
  r59752 | georg.brandl | 2008-01-05 21:46:29 +0100 (Sat, 05 Jan 2008) | 2 lines

  #1719: capitalization error in "UuidCreate".
........
  r59753 | georg.brandl | 2008-01-05 22:02:25 +0100 (Sat, 05 Jan 2008) | 2 lines

  Repair markup.
........
  r59754 | georg.brandl | 2008-01-05 22:10:50 +0100 (Sat, 05 Jan 2008) | 2 lines

  Use markup.
........
  r59757 | christian.heimes | 2008-01-05 22:35:52 +0100 (Sat, 05 Jan 2008) | 1 line

  Final adjustments for #1601
........
  r59758 | guido.van.rossum | 2008-01-05 23:19:06 +0100 (Sat, 05 Jan 2008) | 3 lines

  Patch #1637: fix urlparse for URLs like 'http://x.com?arg=/foo'.
  Fix by John Nagle.
........
  r59759 | guido.van.rossum | 2008-01-05 23:20:01 +0100 (Sat, 05 Jan 2008) | 2 lines

  Add John Nagle (of issue #1637).
........
  r59765 | raymond.hettinger | 2008-01-06 10:02:24 +0100 (Sun, 06 Jan 2008) | 1 line

  Small code simplification.  Forgot that classmethods can be called from intances.
........
  r59766 | martin.v.loewis | 2008-01-06 11:09:48 +0100 (Sun, 06 Jan 2008) | 2 lines

  Use vcbuild for VS 2009.
........
  r59767 | martin.v.loewis | 2008-01-06 12:03:43 +0100 (Sun, 06 Jan 2008) | 2 lines

  Package using VS 2008.
........
  r59768 | martin.v.loewis | 2008-01-06 12:13:16 +0100 (Sun, 06 Jan 2008) | 2 lines

  Don't try to package msvcr90 for the moment.
........
  r59769 | georg.brandl | 2008-01-06 15:17:36 +0100 (Sun, 06 Jan 2008) | 4 lines

  #1696393: don't check for '.' and '..' in ntpath.walk since
  they aren't returned from os.listdir anymore.
  Reported by Michael Haggerty.
........
  r59770 | georg.brandl | 2008-01-06 15:27:15 +0100 (Sun, 06 Jan 2008) | 3 lines

  #1742: don't raise exception on os.path.relpath("a", "a"), but return os.curdir.
  Reported by Jesse Towner.
........
  r59771 | georg.brandl | 2008-01-06 15:33:52 +0100 (Sun, 06 Jan 2008) | 2 lines

  #1591: Clarify docstring of Popen3.
........
  r59772 | georg.brandl | 2008-01-06 16:30:34 +0100 (Sun, 06 Jan 2008) | 2 lines

  #1680: fix context manager example function name.
........
  r59773 | georg.brandl | 2008-01-06 16:34:57 +0100 (Sun, 06 Jan 2008) | 2 lines

  #1755097: document default values for [].sort() and sorted().
........

43 files changed:
Doc/ACKS.txt
Doc/c-api/newtypes.rst
Doc/c-api/utilities.rst
Doc/library/collections.rst
Doc/library/contextlib.rst
Doc/library/decimal.rst
Doc/library/fcntl.rst
Doc/library/functions.rst
Doc/library/msilib.rst
Doc/library/msvcrt.rst
Doc/library/numbers.rst
Doc/library/os.rst
Doc/library/socket.rst
Doc/library/stdtypes.rst
Doc/library/thread.rst
Doc/library/threading.rst
Doc/library/winsound.rst
Doc/reference/compound_stmts.rst
Doc/reference/datamodel.rst
Doc/reference/expressions.rst
Doc/reference/simple_stmts.rst
Doc/whatsnew/2.6.rst
Lib/collections.py
Lib/ntpath.py
Lib/posixpath.py
Lib/tarfile.py
Lib/test/test_collections.py
Lib/test/test_doctest.py
Lib/test/test_ntpath.py
Lib/test/test_posixpath.py
Lib/test/test_socket.py
Lib/test/test_tarfile.py
Lib/test/test_urlparse.py
Lib/urlparse.py
Misc/ACKS
Modules/fcntlmodule.c
Modules/socketmodule.c
Modules/socketmodule.h
PCbuild/build_tkinter.py
Python/dynload_win.c
Python/pystrtod.c
Tools/buildbot/buildmsi.bat
Tools/msi/msi.py

index 5f6e12fa922a0a4b87355cea3751b3acae21c750..32943bddd5203ca6bae5616b1eb5db1d8ea906bd 100644 (file)
@@ -73,6 +73,7 @@ docs@python.org), and we'll be glad to correct the problem.
    * Travis B. Hartwell
    * Tim Hatch
    * Janko Hauser
+   * Thomas Heller
    * Bernhard Herzog
    * Magnus L. Hetland
    * Konrad Hinsen
index 88a4f2fe727845e756e58608fbbc129f63650a5f..8c72ef13761247fd684d7bbd08b2b68fc67b3ac2 100644 (file)
@@ -729,7 +729,7 @@ type objects) *must* have the :attr:`ob_size` field.
    indicated by the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit) and have *NULL*
    values.
 
-   The following bit masks are currently defined; these can be or-ed together using
+   The following bit masks are currently defined; these can be ORed together using
    the ``|`` operator to form the value of the :attr:`tp_flags` field.  The macro
    :cfunc:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and
    checks whether ``tp->tp_flags & f`` is non-zero.
index c4c4b7ebb2daa22e9b3c04c7f1636ee1b58a11bd..c30a62a97a1f7be0c18191bee1d8090a230b6f47 100644 (file)
@@ -197,19 +197,14 @@ Importing Modules
    to find out.  Starting with Python 2.4, a failing import of a module no longer
    leaves the module in ``sys.modules``.
 
-   .. index:: single: modules (in module sys)
-
 
 .. cfunction:: PyObject* PyImport_ImportModuleNoBlock(const char *name)
 
-   .. index::
-      single: `cfunc:PyImport_ImportModule`
-
-   This version of `cfunc:PyImport_ImportModule` does not block. It's intended
+   This version of :cfunc:`PyImport_ImportModule` does not block. It's intended
    to be used in C function which import other modules to execute a function.
    The import may block if another thread holds the import lock. The function
-  `cfunc:PyImport_ImportModuleNoBlock` doesn't block. It first tries to fetch
-   the module from sys.modules and falls back to `cfunc:PyImport_ImportModule`
+   :cfunc:`PyImport_ImportModuleNoBlock` doesn't block. It first tries to fetch
+   the module from sys.modules and falls back to :cfunc:`PyImport_ImportModule`
    unless the the lock is hold. In the latter case the function raises an
    ImportError.
 
@@ -231,9 +226,6 @@ Importing Modules
    Failing imports remove incomplete module objects, like with
    :cfunc:`PyImport_ImportModule`.
 
-   The function is an alias for `cfunc:PyImport_ImportModuleLevel` with -1 as
-   *level*, meaning relative import.
-
 
 .. cfunction:: PyObject* PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
 
@@ -286,9 +278,9 @@ Importing Modules
    :func:`compile`, load the module.  Return a new reference to the module object,
    or *NULL* with an exception set if an error occurred.  Before Python 2.4, the
    module could still be created in error cases.  Starting with Python 2.4, *name*
-   is removed from ``sys.modules`` in error cases, and even if *name* was already
-   in ``sys.modules`` on entry to :cfunc:`PyImport_ExecCodeModule`.  Leaving
-   incompletely initialized modules in ``sys.modules`` is dangerous, as imports of
+   is removed from :attr:`sys.modules` in error cases, and even if *name* was already
+   in :attr:`sys.modules` on entry to :cfunc:`PyImport_ExecCodeModule`.  Leaving
+   incompletely initialized modules in :attr:`sys.modules` is dangerous, as imports of
    such modules have no way to know that the module object is an unknown (and
    probably damaged with respect to the module author's intents) state.
 
index b650462e846ba4dc2f4b54e6375563290dd30171..5b625ee3ae99d57730b35efe7e5c06828409df32 100644 (file)
@@ -419,10 +419,18 @@ Example::
 
            __slots__ = ()
 
+           _fields = ('x', 'y')
+
            def __new__(cls, x, y):
                return tuple.__new__(cls, (x, y))
 
-           _cast = classmethod(tuple.__new__)
+           @classmethod
+           def _make(cls, iterable):
+               'Make a new Point object from a sequence or iterable'
+               result = tuple.__new__(cls, iterable)
+               if len(result) != 2:
+                   raise TypeError('Expected 2 arguments, got %d' % len(result))
+               return result
 
            def __repr__(self):
                return 'Point(x=%r, y=%r)' % self
@@ -433,11 +441,10 @@ Example::
 
            def _replace(self, **kwds):
                'Return a new Point object replacing specified fields with new values'
-               return Point._cast(map(kwds.get, ('x', 'y'), self))
-
-           @property
-           def _fields(self):
-               return ('x', 'y')
+               result = self._make(map(kwds.pop, ('x', 'y'), self))
+               if kwds:
+                   raise ValueError('Got unexpected field names: %r' % kwds.keys())
+               return result
 
            x = property(itemgetter(0))
            y = property(itemgetter(1))
@@ -459,29 +466,28 @@ by the :mod:`csv` or :mod:`sqlite3` modules::
    EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
 
    import csv
-   for emp in map(EmployeeRecord._cast, csv.reader(open("employees.csv", "rb"))):
+   for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
        print(emp.name, emp.title)
 
    import sqlite3
    conn = sqlite3.connect('/companydata')
    cursor = conn.cursor()
    cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
-   for emp in map(EmployeeRecord._cast, cursor.fetchall()):
+   for emp in map(EmployeeRecord._make, cursor.fetchall()):
        print emp.name, emp.title
 
 In addition to the methods inherited from tuples, named tuples support
-three additonal methods and a read-only attribute.
+three additional methods and one attribute.
 
-.. method:: namedtuple._cast(iterable)
+.. method:: namedtuple._make(iterable)
 
-   Class method returning a new instance taking the positional arguments from the *iterable*.
-   Useful for casting existing sequences and iterables to named tuples:
+   Class method that makes a new instance from an existing sequence or iterable.
 
 ::
 
-   >>> t = [11, 22]
-   >>> Point._cast(t)
-   Point(x=11, y=22)
+      >>> t = [11, 22]
+      >>> Point._make(t)
+      Point(x=11, y=22)
 
 .. method:: somenamedtuple._asdict()
 
@@ -507,7 +513,7 @@ three additonal methods and a read-only attribute.
 
 .. attribute:: somenamedtuple._fields
 
-   Return a tuple of strings listing the field names.  This is useful for introspection
+   Tuple of strings listing the field names.  This is useful for introspection
    and for creating new named tuple types from existing named tuples.
 
 ::
index cab2e8c941d0875e2409f0dcaf1bb838c6678653..54d2a19ad4921dcbb0bd63845b480f1173fa39f5 100644 (file)
@@ -21,7 +21,6 @@ Functions provided:
 
    A simple example (this is not recommended as a real way of generating HTML!)::
 
-      from __future__ import with_statement
       from contextlib import contextmanager
 
       @contextmanager
@@ -98,7 +97,6 @@ Functions provided:
 
    And lets you write code like this::
 
-      from __future__ import with_statement
       from contextlib import closing
       import urllib
 
index 218d1c846ac40b3be86bbd592d0e37004a3a7c5e..e29e4ea5fe0977c3686be6f33cc760879c697109 100644 (file)
@@ -794,7 +794,6 @@ the :func:`localcontext` function to temporarily change the active context.
    For example, the following code sets the current decimal precision to 42 places,
    performs a calculation, and then automatically restores the previous context::
 
-      from __future__ import with_statement
       from decimal import localcontext
 
       with localcontext() as ctx:
index 2d7bb9cbb2c1e6c592e777b734c096185ddb7417..5050a7f48783e18b6a9729897d4abd2183c0b882 100644 (file)
@@ -109,7 +109,7 @@ The module defines the following functions:
    * :const:`LOCK_EX` -- acquire an exclusive lock
 
    When *operation* is :const:`LOCK_SH` or :const:`LOCK_EX`, it can also be
-   bit-wise OR'd with :const:`LOCK_NB` to avoid blocking on lock acquisition.
+   bitwise ORed with :const:`LOCK_NB` to avoid blocking on lock acquisition.
    If :const:`LOCK_NB` is used and the lock cannot be acquired, an
    :exc:`IOError` will be raised and the exception will have an *errno*
    attribute set to :const:`EACCES` or :const:`EAGAIN` (depending on the
index ebb7a6cf9eb78ab1547c8604bd64b3a315739372..9463ba76d52bec21808dfce2c96f82278a6c5f25 100644 (file)
@@ -227,7 +227,7 @@ available.  They are listed here in alphabetical order.
    the *flags* argument is it -- the future statements in effect around the call to
    compile are ignored.
 
-   Future statements are specified by bits which can be bitwise or-ed together to
+   Future statements are specified by bits which can be bitwise ORed together to
    specify multiple statements.  The bitfield required to specify a given feature
    can be found as the :attr:`compiler_flag` attribute on the :class:`_Feature`
    instance in the :mod:`__future__` module.
@@ -966,10 +966,11 @@ available.  They are listed here in alphabetical order.
    *cmp* specifies a custom comparison function of two arguments (iterable
    elements) which should return a negative, zero or positive number depending on
    whether the first argument is considered smaller than, equal to, or larger than
-   the second argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``
+   the second argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``.  The default
+   value is ``None``.
 
    *key* specifies a function of one argument that is used to extract a comparison
-   key from each list element: ``key=str.lower``
+   key from each list element: ``key=str.lower``.  The default value is ``None``.
 
    *reverse* is a boolean value.  If set to ``True``, then the list elements are
    sorted as if each comparison were reversed.
index 1c50d822f0b5fdb717870058d9976140bae1c9db..93e7b84e2a156993084bcc2cff38a93aba18c9f2 100644 (file)
@@ -40,7 +40,7 @@ structures.
    exposed.
 
 
-.. function:: UUIDCreate()
+.. function:: UuidCreate()
 
    Return the string representation of a new unique identifier. This wraps the
    Windows API functions :cfunc:`UuidCreate` and :cfunc:`UuidToString`.
index 678ba7a0a6ca78119c2b5a4ac7f3b8f5328b13cf..8a0452f25dfe807ce783c4997ad1dd492e9eb1be 100644 (file)
@@ -67,7 +67,7 @@ File Operations
 .. function:: open_osfhandle(handle, flags)
 
    Create a C runtime file descriptor from the file handle *handle*.  The *flags*
-   parameter should be a bit-wise OR of :const:`os.O_APPEND`, :const:`os.O_RDONLY`,
+   parameter should be a bitwise OR of :const:`os.O_APPEND`, :const:`os.O_RDONLY`,
    and :const:`os.O_TEXT`.  The returned file descriptor may be used as a parameter
    to :func:`os.fdopen` to create a file object.
 
index d0f9c3b83db73df8744a3934edd7a9fa40142852..4202a5092202cb46f5042730e3372c6a612bbe50 100644 (file)
@@ -1,10 +1,10 @@
-
 :mod:`numbers` --- Numeric abstract base classes
 ================================================
 
 .. module:: numbers
    :synopsis: Numeric abstract base classes (Complex, Real, Integral, etc.).
 
+
 The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric abstract
 base classes which progressively define more operations. These concepts also
 provide a way to distinguish exact from inexact types. None of the types defined
index 71e5f36bfcbf8f302849d6f60fe5bc18421f4e8f..ee0cf48bc600c7abef76c057d6dcf5bdb4d668ec 100644 (file)
@@ -7,7 +7,7 @@
 
 
 This module provides a more portable way of using operating system dependent
-functionality than importing a operating system dependent built-in module like
+functionality than importing an operating system dependent built-in module like
 :mod:`posix` or :mod:`nt`. If you just want to read or write a file see
 :func:`open`, if you want to manipulate paths, see the :mod:`os.path`
 module, and if you want to read all the lines in all the files on the
@@ -17,7 +17,7 @@ file and directory handling see the :mod:`shutil` module.
 
 This module searches for an operating system dependent built-in module like
 :mod:`mac` or :mod:`posix` and exports the same functions and data as found
-there.  The design of all Python's built-in operating system dependent modules
+there.  The design of all built-in operating system dependent modules of Python
 is such that as long as the same functionality is available, it uses the same
 interface; for example, the function ``os.stat(path)`` returns stat information
 about *path* in the same format (which happens to have originated with the POSIX
@@ -132,7 +132,7 @@ process and user.
 .. function:: getegid()
 
    Return the effective group id of the current process.  This corresponds to the
-   'set id' bit on the file being executed in the current process. Availability:
+   "set id" bit on the file being executed in the current process. Availability:
    Unix.
 
 
@@ -140,7 +140,7 @@ process and user.
 
    .. index:: single: user; effective id
 
-   Return the current process' effective user id. Availability: Unix.
+   Return the current process's effective user id. Availability: Unix.
 
 
 .. function:: getgid()
@@ -162,7 +162,7 @@ process and user.
    process.  For most purposes, it is more useful to use the environment variable
    :envvar:`LOGNAME` to find out who the user is, or
    ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
-   effective user ID. Availability: Unix.
+   effective user id. Availability: Unix.
 
 
 .. function:: getpgid(pid)
@@ -196,7 +196,7 @@ process and user.
 
    .. index:: single: user; id
 
-   Return the current process' user id. Availability: Unix.
+   Return the current process's user id. Availability: Unix.
 
 
 .. function:: getenv(varname[, value])
@@ -245,20 +245,20 @@ process and user.
 
    Set the list of supplemental group ids associated with the current process to
    *groups*. *groups* must be a sequence, and each element must be an integer
-   identifying a group. This operation is typical available only to the superuser.
+   identifying a group. This operation is typically available only to the superuser.
    Availability: Unix.
 
 
 .. function:: setpgrp()
 
-   Calls the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
+   Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
    which version is implemented (if any).  See the Unix manual for the semantics.
    Availability: Unix.
 
 
 .. function:: setpgid(pid, pgrp)
 
-   Calls the system call :cfunc:`setpgid` to set the process group id of the
+   Call the system call :cfunc:`setpgid` to set the process group id of the
    process with id *pid* to the process group with id *pgrp*.  See the Unix manual
    for the semantics. Availability: Unix.
 
@@ -275,13 +275,13 @@ process and user.
 
 .. function:: getsid(pid)
 
-   Calls the system call :cfunc:`getsid`.  See the Unix manual for the semantics.
+   Call the system call :cfunc:`getsid`.  See the Unix manual for the semantics.
    Availability: Unix.
 
 
 .. function:: setsid()
 
-   Calls the system call :cfunc:`setsid`.  See the Unix manual for the semantics.
+   Call the system call :cfunc:`setsid`.  See the Unix manual for the semantics.
    Availability: Unix.
 
 
@@ -289,7 +289,7 @@ process and user.
 
    .. index:: single: user; id, setting
 
-   Set the current process' user id. Availability: Unix.
+   Set the current process's user id. Availability: Unix.
 
 
 .. placed in this section since it relates to errno.... a little weak
@@ -301,7 +301,7 @@ process and user.
 
 .. function:: umask(mask)
 
-   Set the current numeric umask and returns the previous umask. Availability:
+   Set the current numeric umask and return the previous umask. Availability:
    Unix, Windows.
 
 
@@ -491,9 +491,10 @@ by file descriptors.
 
 .. function:: lseek(fd, pos, how)
 
-   Set the current position of file descriptor *fd* to position *pos*, modified by
-   *how*: ``0`` to set the position relative to the beginning of the file; ``1`` to
-   set it relative to the current position; ``2`` to set it relative to the end of
+   Set the current position of file descriptor *fd* to position *pos*, modified
+   by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
+   beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
+   current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
    the file. Availability: Macintosh, Unix, Windows.
 
 
@@ -522,7 +523,7 @@ by file descriptors.
 
    Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
    slave)`` for the pty and the tty, respectively. For a (slightly) more portable
-   approach, use the :mod:`pty` module. Availability: Macintosh, Some flavors of
+   approach, use the :mod:`pty` module. Availability: Macintosh, some flavors of
    Unix.
 
 
@@ -543,7 +544,7 @@ by file descriptors.
       This function is intended for low-level I/O and must be applied to a file
       descriptor as returned by :func:`open` or :func:`pipe`.  To read a "file object"
       returned by the built-in function :func:`open` or by :func:`popen` or
-      :func:`fdopen`, or ``sys.stdin``, use its :meth:`read` or :meth:`readline`
+      :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline`
       methods.
 
 
@@ -576,7 +577,7 @@ by file descriptors.
       This function is intended for low-level I/O and must be applied to a file
       descriptor as returned by :func:`open` or :func:`pipe`.  To write a "file
       object" returned by the built-in function :func:`open` or by :func:`popen` or
-      :func:`fdopen`, or ``sys.stdout`` or ``sys.stderr``, use its :meth:`write`
+      :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
       method.
 
 The following data items are available for use in constructing the *flags*
@@ -594,7 +595,7 @@ platforms.  For descriptions of their availability and use, consult
           O_TRUNC
 
    Options for the *flag* argument to the :func:`open` function. These can be
-   bit-wise OR'd together. Availability: Macintosh, Unix, Windows.
+   combined using the bitwise OR operator ``|``. Availability: Macintosh, Unix, Windows.
 
 
 .. data:: O_DSYNC
@@ -619,7 +620,7 @@ platforms.  For descriptions of their availability and use, consult
           O_TEXT
 
    Options for the *flag* argument to the :func:`open` function. These can be
-   bit-wise OR'd together. Availability: Windows.
+   combined using the bitwise OR operator ``|``. Availability: Windows.
 
 
 .. data:: O_DIRECT
@@ -749,7 +750,7 @@ Files and Directories
 .. function:: chmod(path, mode)
 
    Change the mode of *path* to the numeric *mode*. *mode* may take one of the
-   following values (as defined in the :mod:`stat` module) or bitwise or-ed
+   following values (as defined in the :mod:`stat` module) or bitwise ORed
    combinations of them:
 
    * ``stat.S_ISUID``
@@ -803,7 +804,7 @@ Files and Directories
 
 .. function:: lchown(path, uid, gid)
 
-   Change the owner and group id of *path* to the numeric *uid* and gid. This
+   Change the owner and group id of *path* to the numeric *uid* and *gid*. This
    function will not follow symbolic links. Availability: Macintosh, Unix.
 
 
@@ -857,19 +858,19 @@ Files and Directories
 
 .. function:: major(device)
 
-   Extracts the device major number from a raw device number (usually the
+   Extract the device major number from a raw device number (usually the
    :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
 
 
 .. function:: minor(device)
 
-   Extracts the device minor number from a raw device number (usually the
+   Extract the device minor number from a raw device number (usually the
    :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
 
 
 .. function:: makedev(major, minor)
 
-   Composes a raw device number from the major and minor device numbers.
+   Compose a raw device number from the major and minor device numbers.
 
 
 .. function:: mkdir(path[, mode])
@@ -897,7 +898,7 @@ Files and Directories
    .. note::
 
       :func:`makedirs` will become confused if the path elements to create include
-      *os.pardir*.
+      :data:`os.pardir`.
 
    This function handles UNC paths correctly.
 
@@ -954,7 +955,7 @@ Files and Directories
 
    .. index:: single: directory; deleting
 
-   Removes directories recursively.  Works like :func:`rmdir` except that, if the
+   Remove directories recursively.  Works like :func:`rmdir` except that, if the
    leaf directory is successfully removed, :func:`removedirs`  tries to
    successively remove every parent directory mentioned in  *path* until an error
    is raised (which is ignored, because it generally means that a parent directory
@@ -968,7 +969,7 @@ Files and Directories
 
    Rename the file or directory *src* to *dst*.  If *dst* is a directory,
    :exc:`OSError` will be raised.  On Unix, if *dst* exists and is a file, it will
-   be removed silently if the user has permission.  The operation may fail on some
+   be replaced silently if the user has permission.  The operation may fail on some
    Unix flavors if *src* and *dst* are on different filesystems.  If successful,
    the renaming will be an atomic operation (this is a POSIX requirement).  On
    Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
@@ -1000,7 +1001,7 @@ Files and Directories
    object whose attributes correspond to the members of the :ctype:`stat`
    structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
    number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
-   :attr:`st_uid` (user ID of owner), :attr:`st_gid` (group ID of owner),
+   :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
    :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
    access), :attr:`st_mtime` (time of most recent content modification),
    :attr:`st_ctime` (platform dependent; time of most recent metadata change on
@@ -1014,10 +1015,6 @@ Files and Directories
       926L
       >>>
 
-   If :func:`stat_float_times` returns true, the time values are floats, measuring
-   seconds. Fractions of a second may be reported if the system supports that. On
-   Mac OS, the times are always floats. See :func:`stat_float_times` for further
-   discussion.
 
    On some Unix systems (such as Linux), the following attributes may also be
    available: :attr:`st_blocks` (number of blocks allocated for file),
@@ -1131,8 +1128,8 @@ Files and Directories
       single: directory; walking
       single: directory; traversal
 
-   :func:`walk` generates the file names in a directory tree, by walking the tree
-   either top down or bottom up. For each directory in the tree rooted at directory
+   Generate the file names in a directory tree by walking the tree
+   either top-down or bottom-up. For each directory in the tree rooted at directory
    *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
    filenames)``.
 
@@ -1143,34 +1140,34 @@ Files and Directories
    (which begins with *top*) to a file or directory in *dirpath*, do
    ``os.path.join(dirpath, name)``.
 
-   If optional argument *topdown* is true or not specified, the triple for a
+   If optional argument *topdown* is ``True`` or not specified, the triple for a
    directory is generated before the triples for any of its subdirectories
-   (directories are generated top down).  If *topdown* is false, the triple for a
+   (directories are generated top-down).  If *topdown* is ``False``, the triple for a
    directory is generated after the triples for all of its subdirectories
-   (directories are generated bottom up).
+   (directories are generated bottom-up).
 
-   When *topdown* is true, the caller can modify the *dirnames* list in-place
+   When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
    (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
    recurse into the subdirectories whose names remain in *dirnames*; this can be
    used to prune the search, impose a specific order of visiting, or even to inform
    :func:`walk` about directories the caller creates or renames before it resumes
-   :func:`walk` again.  Modifying *dirnames* when *topdown* is false is
+   :func:`walk` again.  Modifying *dirnames* when *topdown* is ``False`` is
    ineffective, because in bottom-up mode the directories in *dirnames* are
    generated before *dirpath* itself is generated.
 
-   By default errors from the ``os.listdir()`` call are ignored.  If optional
+   By default errors from the :func:`listdir` call are ignored.  If optional
    argument *onerror* is specified, it should be a function; it will be called with
    one argument, an :exc:`OSError` instance.  It can report the error to continue
    with the walk, or raise the exception to abort the walk.  Note that the filename
    is available as the ``filename`` attribute of the exception object.
 
    By default, :func:`walk` will not walk down into symbolic links that resolve to
-   directories. Set *followlinks* to True to visit directories pointed to by
+   directories. Set *followlinks* to ``True`` to visit directories pointed to by
    symlinks, on systems that support them.
 
    .. note::
 
-      Be aware that setting *followlinks* to true can lead to infinite recursion if a
+      Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
       link points to a parent directory of itself. :func:`walk` does not keep track of
       the directories it visited already.
 
@@ -1193,10 +1190,10 @@ Files and Directories
           if 'CVS' in dirs:
               dirs.remove('CVS')  # don't visit CVS directories
 
-   In the next example, walking the tree bottom up is essential: :func:`rmdir`
+   In the next example, walking the tree bottom-up is essential: :func:`rmdir`
    doesn't allow deleting a directory before the directory is empty::
 
-      # Delete everything reachable from the directory named in 'top',
+      # Delete everything reachable from the directory named in "top",
       # assuming there are no symbolic links.
       # CAUTION:  This is dangerous!  For example, if top == '/', it
       # could delete all your disk files.
@@ -1244,19 +1241,19 @@ to be ignored.
 
    These functions all execute a new program, replacing the current process; they
    do not return.  On Unix, the new executable is loaded into the current process,
-   and will have the same process ID as the caller.  Errors will be reported as
+   and will have the same process id as the caller.  Errors will be reported as
    :exc:`OSError` exceptions.
 
-   The ``'l'`` and ``'v'`` variants of the :func:`exec\*` functions differ in how
-   command-line arguments are passed.  The ``'l'`` variants are perhaps the easiest
+   The "l" and "v" variants of the :func:`exec\*` functions differ in how
+   command-line arguments are passed.  The "l" variants are perhaps the easiest
    to work with if the number of parameters is fixed when the code is written; the
    individual parameters simply become additional parameters to the :func:`execl\*`
-   functions.  The ``'v'`` variants are good when the number of parameters is
+   functions.  The "v" variants are good when the number of parameters is
    variable, with the arguments being passed in a list or tuple as the *args*
    parameter.  In either case, the arguments to the child process should start with
    the name of the command being run, but this is not enforced.
 
-   The variants which include a ``'p'`` near the end (:func:`execlp`,
+   The variants which include a "p" near the end (:func:`execlp`,
    :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
    :envvar:`PATH` environment variable to locate the program *file*.  When the
    environment is being replaced (using one of the :func:`exec\*e` variants,
@@ -1267,7 +1264,7 @@ to be ignored.
    path.
 
    For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
-   that these all end in ``'e'``), the *env* parameter must be a mapping which is
+   that these all end in "e"), the *env* parameter must be a mapping which is
    used to define the environment variables for the new process; the :func:`execl`,
    :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
    inherit the environment of the current process. Availability: Macintosh, Unix,
@@ -1284,7 +1281,7 @@ to be ignored.
       The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
       be used in the child process after a :func:`fork`.
 
-The following exit codes are a defined, and can be used with :func:`_exit`,
+The following exit codes are defined and can be used with :func:`_exit`,
 although they are not required.  These are typically used for system programs
 written in Python, such as a mail server's external command delivery program.
 
@@ -1400,7 +1397,7 @@ written in Python, such as a mail server's external command delivery program.
 
 .. function:: fork()
 
-   Fork a child process.  Return ``0`` in the child, the child's process id in the
+   Fork a child process.  Return ``0`` in the child and the child's process id in the
    parent. Availability: Macintosh, Unix.
 
 
@@ -1410,7 +1407,7 @@ written in Python, such as a mail server's external command delivery program.
    terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
    new child's process id in the parent, and *fd* is the file descriptor of the
    master end of the pseudo-terminal.  For a more portable approach, use the
-   :mod:`pty` module. Availability: Macintosh, Some flavors of Unix.
+   :mod:`pty` module. Availability: Macintosh, some flavors of Unix.
 
 
 .. function:: kill(pid, sig)
@@ -1469,22 +1466,22 @@ written in Python, such as a mail server's external command delivery program.
    spawning new processes and retrieving their results; using that module is
    preferable to using these functions.)
 
-   If *mode* is :const:`P_NOWAIT`, this function returns the process ID of the new
+   If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
    process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
    exits normally, or ``-signal``, where *signal* is the signal that killed the
-   process.  On Windows, the process ID will actually be the process handle, so can
+   process.  On Windows, the process id will actually be the process handle, so can
    be used with the :func:`waitpid` function.
 
-   The ``'l'`` and ``'v'`` variants of the :func:`spawn\*` functions differ in how
-   command-line arguments are passed.  The ``'l'`` variants are perhaps the easiest
+   The "l" and "v" variants of the :func:`spawn\*` functions differ in how
+   command-line arguments are passed.  The "l" variants are perhaps the easiest
    to work with if the number of parameters is fixed when the code is written; the
    individual parameters simply become additional parameters to the
-   :func:`spawnl\*` functions.  The ``'v'`` variants are good when the number of
+   :func:`spawnl\*` functions.  The "v" variants are good when the number of
    parameters is variable, with the arguments being passed in a list or tuple as
    the *args* parameter.  In either case, the arguments to the child process must
    start with the name of the command being run.
 
-   The variants which include a second ``'p'`` near the end (:func:`spawnlp`,
+   The variants which include a second "p" near the end (:func:`spawnlp`,
    :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
    :envvar:`PATH` environment variable to locate the program *file*.  When the
    environment is being replaced (using one of the :func:`spawn\*e` variants,
@@ -1495,7 +1492,7 @@ written in Python, such as a mail server's external command delivery program.
    appropriate absolute or relative path.
 
    For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
-   (note that these all end in ``'e'``), the *env* parameter must be a mapping
+   (note that these all end in "e"), the *env* parameter must be a mapping
    which is used to define the environment variables for the new process; the
    :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
    the new process to inherit the environment of the current process.
@@ -1518,7 +1515,7 @@ written in Python, such as a mail server's external command delivery program.
 
    Possible values for the *mode* parameter to the :func:`spawn\*` family of
    functions.  If either of these values is given, the :func:`spawn\*` functions
-   will return as soon as the new process has been created, with the process ID as
+   will return as soon as the new process has been created, with the process id as
    the return value. Availability: Macintosh, Unix, Windows.
 
 
@@ -1569,8 +1566,8 @@ written in Python, such as a mail server's external command delivery program.
 
    Execute the command (a string) in a subshell.  This is implemented by calling
    the Standard C function :cfunc:`system`, and has the same limitations.  Changes
-   to ``posix.environ``, ``sys.stdin``, etc. are not reflected in the environment
-   of the executed command.
+   to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the
+   environment of the executed command.
 
    On Unix, the return value is the exit status of the process encoded in the
    format specified for :func:`wait`.  Note that POSIX does not specify the meaning
@@ -1681,32 +1678,32 @@ used to determine the disposition of a process.
 
 .. function:: WCOREDUMP(status)
 
-   Returns ``True`` if a core dump was generated for the process, otherwise it
-   returns ``False``. Availability: Macintosh, Unix.
+   Return ``True`` if a core dump was generated for the process, otherwise
+   return ``False``. Availability: Macintosh, Unix.
 
 
 .. function:: WIFCONTINUED(status)
 
-   Returns ``True`` if the process has been continued from a job control stop,
-   otherwise it returns ``False``. Availability: Unix.
+   Return ``True`` if the process has been continued from a job control stop,
+   otherwise return ``False``. Availability: Unix.
 
 
 .. function:: WIFSTOPPED(status)
 
-   Returns ``True`` if the process has been stopped, otherwise it returns
+   Return ``True`` if the process has been stopped, otherwise return
    ``False``. Availability: Unix.
 
 
 .. function:: WIFSIGNALED(status)
 
-   Returns ``True`` if the process exited due to a signal, otherwise it returns
+   Return ``True`` if the process exited due to a signal, otherwise return
    ``False``. Availability: Macintosh, Unix.
 
 
 .. function:: WIFEXITED(status)
 
-   Returns ``True`` if the process exited using the :manpage:`exit(2)` system call,
-   otherwise it returns ``False``. Availability: Macintosh, Unix.
+   Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
+   otherwise return ``False``. Availability: Macintosh, Unix.
 
 
 .. function:: WEXITSTATUS(status)
@@ -1783,7 +1780,7 @@ Miscellaneous System Information
    defined for those names by the host operating system. This can be used to
    determine the set of names known to the system. Availability: Macintosh, Unix.
 
-The follow data values are used to support path manipulation operations.  These
+The following data values are used to support path manipulation operations.  These
 are defined for all platforms.
 
 Higher-level operations on pathnames are defined in the :mod:`os.path` module.
index a6557e104fe7ddd8aa807d21b2c942c2cf2761ed..cc1615058813dcdda5604b5357b32466a11616b5 100644 (file)
@@ -155,6 +155,12 @@ The module :mod:`socket` exports the following constants and functions:
    in the Unix header files are defined; for a few symbols, default values are
    provided.
 
+.. data:: SIO_*
+          RCVALL_*
+          
+   Constants for Windows' WSAIoctl(). The constants are used as arguments to the
+   :meth:`ioctl` method of socket objects.
+   
 
 .. data:: has_ipv6
 
@@ -524,6 +530,14 @@ correspond to Unix system calls applicable to sockets.
    contents of the buffer (see the optional built-in module :mod:`struct` for a way
    to decode C structures encoded as strings).
 
+   
+.. method:: socket.ioctl(control, option)
+
+   :platform: Windows 
+   
+   The `meth:ioctl` method is a limited interface to the WSAIoctl system
+   interface. Please refer to the MSDN documentation for more information.
+   
 
 .. method:: socket.listen(backlog)
 
@@ -822,3 +836,28 @@ sends traffic to the first one connected successfully. ::
    s.close()
    print('Received', repr(data))
 
+   
+The last example shows how to write a very simple network sniffer with raw
+sockets on Windows. The example requires administrator priviliges to modify
+the interface::
+
+   import socket
+
+   # the public network interface
+   HOST = socket.gethostbyname(socket.gethostname())
+   
+   # create a raw socket and bind it to the public interface
+   s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
+   s.bind((HOST, 0))
+   
+   # Include IP headers
+   s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
+   
+   # receive all packages
+   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
+   
+   # receive a package
+   print s.recvfrom(65565)
+   
+   # disabled promiscous mode
+   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
index 554cbc5a8553f56da59fb787a635f0fe0527b121..92183a48831ab58ba62539963ebb5e38ee1fd3a7 100644 (file)
@@ -352,6 +352,23 @@ Notes:
    or "-" for Not a Number (NaN) and positive or negative infinity.
    
 
+All :class:`numbers.Real` types (:class:`int` and
+:class:`float`) also include the following operations:
+
++--------------------+--------------------------------+--------+
+| Operation          | Result                         | Notes  |
++====================+================================+========+
+| ``trunc(x)``       | *x* truncated to Integral      |        |
++--------------------+--------------------------------+--------+
+| ``round(x[, n])``  | *x* rounded to n digits,       |        |
+|                    | rounding half to even. If n is |        |
+|                    | omitted, it defaults to 0.     |        |
++--------------------+--------------------------------+--------+
+| ``math.floor(x)``  | the greatest Integral <= *x*   |        |
++--------------------+--------------------------------+--------+
+| ``math.ceil(x)``   | the least Integral >= *x*      |        |
++--------------------+--------------------------------+--------+
+
 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
 
 
@@ -366,7 +383,7 @@ Integers support additional operations that make sense only for bit-strings.
 Negative numbers are treated as their 2's complement value (this assumes a
 sufficiently large number of bits that no overflow occurs during the operation).
 
-The priorities of the binary bit-wise operations are all lower than the numeric
+The priorities of the binary bitwise operations are all lower than the numeric
 operations and higher than the comparisons; the unary operation ``~`` has the
 same priority as the other unary numeric operations (``+`` and ``-``).
 
@@ -1319,10 +1336,11 @@ Notes:
    *cmp* specifies a custom comparison function of two arguments (list items) which
    should return a negative, zero or positive number depending on whether the first
    argument is considered smaller than, equal to, or larger than the second
-   argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``
+   argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``.  The default value
+   is ``None``.
 
    *key* specifies a function of one argument that is used to extract a comparison
-   key from each list element: ``key=str.lower``
+   key from each list element: ``key=str.lower``.  The default value is ``None``.
 
    *reverse* is a boolean value.  If set to ``True``, then the list elements are
    sorted as if each comparison were reversed.
@@ -2005,7 +2023,12 @@ Files have the following methods:
    argument is optional and defaults to  ``os.SEEK_SET`` or ``0`` (absolute file
    positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
    current position) and ``os.SEEK_END`` or ``2``  (seek relative to the file's
-   end).  There is no return value.  Note that if the file is opened for appending
+   end).  There is no return value.
+   
+   For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
+   ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
+
+   Note that if the file is opened for appending
    (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
    next write.  If the file is only opened for writing in append mode (mode
    ``'a'``), this method is essentially a no-op, but it remains useful for files
@@ -2138,7 +2161,7 @@ to be provided for a context manager object to define a runtime context:
    the context expression in a :keyword:`with` statement.
 
    An example of a context manager that returns a related object is the one
-   returned by ``decimal.Context.get_manager()``. These managers set the active
+   returned by :func:`decimal.localcontext`. These managers set the active
    decimal context to a copy of the original decimal context and then return the
    copy. This allows changes to be made to the current decimal context in the body
    of the :keyword:`with` statement without affecting code outside the
index 867a1ff1370c6a7d9009df91a827184e6715afde..31d58e784a3ef6fc9de703ae1808d5142c3ea5c3 100644 (file)
@@ -132,7 +132,6 @@ Lock objects have the following methods:
 In addition to these methods, lock objects can also be used via the
 :keyword:`with` statement, e.g.::
 
-   from __future__ import with_statement
    import thread
 
    a_lock = thread.allocate_lock()
index 1b82e4b6d3347037d12431e9f10275d26e3df688..c015372855cc173ba57d2689f003ef6ae2c7b966 100644 (file)
@@ -716,7 +716,6 @@ Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
 :class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
 :keyword:`with` statement context managers.  For example::
 
-   from __future__ import with_statement
    import threading
 
    some_rlock = threading.RLock()
index 923c7c4a1fc4598f0fbe1934c0fa5d656ac84f45..308884891eb300566dbd49054ae003ee86bc7062 100644 (file)
@@ -32,7 +32,7 @@ provided by Windows platforms.  It includes functions and several constants.
 
    Call the underlying :cfunc:`PlaySound` function from the Platform API.  The
    *sound* parameter may be a filename, audio data as a string, or ``None``.  Its
-   interpretation depends on the value of *flags*, which can be a bit-wise ORed
+   interpretation depends on the value of *flags*, which can be a bitwise ORed
    combination of the constants described below.  If the system indicates an error,
    :exc:`RuntimeError` is raised.
 
index 927930a27e5dd091bb28bbfa1342a4be60514d9d..ffd7423382ac1c9ba119659554f614e86928aa45 100644 (file)
@@ -78,7 +78,10 @@ on a separate line for clarity.
 The :keyword:`if` statement
 ===========================
 
-.. index:: statement: if
+.. index::
+   statement: if
+   keyword: elif
+   keyword: else
            keyword: elif
            keyword: else
 
@@ -105,6 +108,7 @@ The :keyword:`while` statement
    statement: while
    keyword: else
    pair: loop; statement
+   keyword: else
 
 The :keyword:`while` statement is used for repeated execution as long as an
 expression is true:
@@ -139,6 +143,9 @@ The :keyword:`for` statement
    keyword: else
    pair: target; list
    pair: loop; statement
+   keyword: in
+   keyword: else
+   pair: target; list
    object: sequence
 
 The :keyword:`for` statement is used to iterate over the elements of a sequence
@@ -208,7 +215,10 @@ returns the list ``[0, 1, 2]``.
 The :keyword:`try` statement
 ============================
 
-.. index:: statement: try
+.. index::
+   statement: try
+   keyword: except
+   keyword: finally
 .. index:: keyword: except
 
 The :keyword:`try` statement specifies exception handlers and/or cleanup code
@@ -223,7 +233,8 @@ for a group of statements:
    try2_stmt: "try" ":" `suite`
             : "finally" ":" `suite`
 
-The :keyword:`except` clause(s) specify one or more exception handlers.  When no
+
+The :keyword:`except` clause(s) specify one or more exception handlers. When no
 exception occurs in the :keyword:`try` clause, no exception handler is executed.
 When an exception occurs in the :keyword:`try` suite, a search for an exception
 handler is started.  This search inspects the except clauses in turn until one
@@ -379,6 +390,10 @@ The execution of the :keyword:`with` statement proceeds as follows:
    location for the kind of exit that was taken.
 
 
+   In Python 2.5, the :keyword:`with` statement is only allowed when the
+   ``with_statement`` feature has been enabled.  It is always enabled in
+   Python 2.6.
+
 .. seealso::
 
    :pep:`0343` - The "with" statement
@@ -393,8 +408,10 @@ Function definitions
 ====================
 
 .. index::
-   pair: function; definition
    statement: def
+   pair: function; definition
+   pair: function; name
+   pair: name; binding
    object: user-defined function
    object: function
    pair: function; name
@@ -513,13 +530,13 @@ Class definitions
 =================
 
 .. index::
-   pair: class; definition
-   statement: class
    object: class
-   single: inheritance
+   statement: class
+   pair: class; definition
    pair: class; name
    pair: name; binding
    pair: execution; frame
+   single: inheritance
 
 A class definition defines a class object (see section :ref:`types`):
 
@@ -554,13 +571,13 @@ is equivalent to ::
    Foo = f1(arg)(f2(Foo))
 
 **Programmer's note:** Variables defined in the class definition are class
-variables; they are shared by all instances.  To define instance variables, they
-must be given a value in the :meth:`__init__` method or in another method.  Both
-class and instance variables are accessible through the notation
-"``self.name``", and an instance variable hides a class variable with the same
-name when accessed in this way.  Class variables with immutable values can be
-used as defaults for instance variables.  Descriptors can be used to create
-instance variables with different implementation details.
+can be set in a method with ``self.name = value``.  Both class and instance
+variables are accessible through the notation "``self.name``", and an instance
+variable hides a class variable with the same name when accessed in this way.
+Class variables can be used as defaults for instance variables, but using
+mutable values there can lead to unexpected results.  For :term:`new-style
+class`\es, descriptors can be used to create instance variables with different
+implementation details.
 
 .. XXX add link to descriptor docs above
 
index 3c7f8e6ed031d790c7b60152910e7a55fc60a644..6acd25a7602273781fab6e72b252224111d5c62f 100644 (file)
@@ -1011,16 +1011,17 @@ implemented before for compatibility concerns, like the method resolution order
 in case of multiple inheritance.
 
 This manual is not up-to-date with respect to new-style classes.  For now,
-please see http://www.python.org/doc/newstyle.html for more information.
+please see http://www.python.org/doc/newstyle/ for more information.
 
 .. index::
-   single: class
-   single: class
-   single: class
+   single: class; new-style
+   single: class; classic
+   single: class; old-style
 
 The plan is to eventually drop old-style classes, leaving only the semantics of
 new-style classes.  This change will probably only be feasible in Python 3.0.
-new-style classic old-style
+
+XXX Remove old style classes from docs
 
 
 .. _specialnames:
@@ -1902,6 +1903,18 @@ For more information on context managers, see :ref:`typecontextmanager`.
 
 .. rubric:: Footnotes
 
+.. [#] Since Python 2.2, a gradual merging of types and classes has been started that
+   makes this and a few other assertions made in this manual not 100% accurate and
+   complete: for example, it *is* now possible in some cases to change an object's
+   type, under certain controlled conditions.  Until this manual undergoes
+   extensive revision, it must now be taken as authoritative only regarding
+   "classic classes", that are still the default, for compatibility purposes, in
+   Python 2.2 and 2.3.  For more information, see
+   http://www.python.org/doc/newstyle/.
+
+.. [#] This, and other statements, are only roughly true for instances of new-style
+   classes.
+
 .. [#] A descriptor can define any combination of :meth:`__get__`,
    :meth:`__set__` and :meth:`__delete__`.  If it does not define :meth:`__get__`,
    then accessing the attribute even on an instance will return the descriptor
index cf95636da748dce8ff88a22ce07d1e28be0d0971..380d265be99da5f9df95bfc59a5522cfd4859dd3 100644 (file)
@@ -769,7 +769,7 @@ float result is delivered. For example, ``10**2`` returns ``100``, but
 
 Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
 Raising a negative number to a fractional power results in a :class:`complex`
-number. (Since Python 2.6. In earlier versions it raised a :exc:`ValueError`.)
+number. (In earlier versions it raised a :exc:`ValueError`.)
 
 
 .. _unary:
@@ -779,9 +779,9 @@ Unary arithmetic operations
 
 .. index::
    triple: unary; arithmetic; operation
-   triple: unary; bit-wise; operation
+   triple: unary; bitwise; operation
 
-All unary arithmetic (and bit-wise) operations have the same priority:
+All unary arithmetic (and bitwise) operations have the same priority:
 
 .. productionlist::
    u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
@@ -798,9 +798,10 @@ The unary ``+`` (plus) operator yields its numeric argument unchanged.
 
 .. index:: single: inversion
 
-The unary ``~`` (invert) operator yields the bit-wise inversion of its integer
-argument.  The bit-wise inversion of ``x`` is defined as ``-(x+1)``.  It only
-applies to integral numbers.
+
+The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
+long integer argument.  The bitwise inversion of ``x`` is defined as
+``-(x+1)``.  It only applies to integral numbers.
 
 .. index:: exception: TypeError
 
@@ -905,10 +906,10 @@ by *n* bits is defined as multiplication with ``pow(2,n)``.
 
 .. _bitwise:
 
-Binary bit-wise operations
-==========================
+Binary bitwise operations
+=========================
 
-.. index:: triple: binary; bit-wise; operation
+.. index:: triple: binary; bitwise; operation
 
 Each of the three bitwise operations has a different priority level:
 
@@ -917,20 +918,20 @@ Each of the three bitwise operations has a different priority level:
    xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
    or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
 
-.. index:: pair: bit-wise; and
+.. index:: pair: bitwise; and
 
 The ``&`` operator yields the bitwise AND of its arguments, which must be
 integers.
 
 .. index::
-   pair: bit-wise; xor
+   pair: bitwise; xor
    pair: exclusive; or
 
 The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
 must be integers.
 
 .. index::
-   pair: bit-wise; or
+   pair: bitwise; or
    pair: inclusive; or
 
 The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
index a82200698345bea37a579b817b25eccc1fa3aaaa..1dc49f33316e7c9920e498e97301c48c620df731 100644 (file)
@@ -33,7 +33,9 @@ simple statements is:
 Expression statements
 =====================
 
-.. index:: pair: expression; statement
+.. index::
+   pair: expression; statement
+   pair: expression; list
 .. index:: pair: expression; list
 
 Expression statements are used (mostly interactively) to compute and write a
@@ -327,7 +329,9 @@ is determined when the interpreter starts.
 The :keyword:`pass` statement
 =============================
 
-.. index:: statement: pass
+.. index::
+   statement: pass
+   pair: null; operation
            pair: null; operation
 
 .. productionlist::
@@ -347,9 +351,10 @@ code needs to be executed, for example::
 The :keyword:`del` statement
 ============================
 
-.. index:: statement: del
-           pair: deletion; target
-           triple: deletion; target; list
+.. index::
+   statement: del
+   pair: deletion; target
+   triple: deletion; target; list
 
 .. productionlist::
    del_stmt: "del" `target_list`
@@ -386,9 +391,10 @@ the sliced object).
 The :keyword:`return` statement
 ===============================
 
-.. index:: statement: return
-           pair: function; definition
-           pair: class; definition
+.. index::
+   statement: return
+   pair: function; definition
+   pair: class; definition
 
 .. productionlist::
    return_stmt: "return" [`expression_list`]
@@ -418,23 +424,34 @@ raised.
 The :keyword:`yield` statement
 ==============================
 
+.. index::
+   statement: yield
+   single: generator; function
+   single: generator; iterator
+   single: function; generator
+   exception: StopIteration
+
 .. productionlist::
    yield_stmt: `yield_expression`
 
-The yield statement is nothing but a yield expression used as a statement,
-see :ref:`yieldexpr`.
-
+The :keyword:`yield` statement is only used when defining a generator function,
+and is only used in the body of the generator function. Using a :keyword:`yield`
+statement in a function definition is sufficient to cause that definition to
+create a generator function instead of a normal function.
+>>>>>>> .merge-right.r59773
 
 .. _raise:
 
 The :keyword:`raise` statement
 ==============================
 
-.. index:: statement: raise
-           pair: raising; exception
+.. index::
+   statement: raise
+   single: exception
+   pair: raising; exception
 
 .. productionlist::
-   raise_stmt: "raise" [`expression` ["from" `expression`]]
+   raise_stmt: "raise" [`expression` ["," `expression` ["," `expression`]]]
 
 If no expressions are present, :keyword:`raise` re-raises the last exception
 that was active in the current scope.  If no exception is active in the current
@@ -476,10 +493,11 @@ and information about handling exceptions is in section :ref:`try`.
 The :keyword:`break` statement
 ==============================
 
-.. index:: statement: break
-           statement: for
-           statement: while
-           pair: loop; statement
+.. index::
+   statement: break
+   statement: for
+   statement: while
+   pair: loop; statement
 
 .. productionlist::
    break_stmt: "break"
@@ -509,11 +527,12 @@ really leaving the loop.
 The :keyword:`continue` statement
 =================================
 
-.. index:: statement: continue
-           statement: for
-           statement: while
-           pair: loop; statement
-           keyword: finally
+.. index::
+   statement: continue
+   statement: for
+   statement: while
+   pair: loop; statement
+   keyword: finally
 
 .. productionlist::
    continue_stmt: "continue"
@@ -631,6 +650,7 @@ raise a :exc:`SyntaxError`.
 
 .. index::
    keyword: from
+   statement: from
    triple: hierarchical; module; names
    single: packages
    single: __init__.py
@@ -731,13 +751,13 @@ after the script is executed.
 The :keyword:`global` statement
 ===============================
 
-.. index:: statement: global
+.. index::
+   statement: global
+   triple: global; name; binding
 
 .. productionlist::
    global_stmt: "global" `identifier` ("," `identifier`)*
 
-.. index:: triple: global; name; binding
-
 The :keyword:`global` statement is a declaration which holds for the entire
 current code block.  It means that the listed identifiers are to be interpreted
 as globals.  It would be impossible to assign to a global variable without
@@ -789,11 +809,6 @@ because the default behavior for binding is to search the local namespace
 first.  The statement allows encapsulated code to rebind variables outside of
 the local scope besides the global (module) scope.
 
-.. note::
-
-   The outer scope for :keyword:`nonlocal` statements cannot be the module
-   scope.
-
 .. XXX not implemented
    The :keyword:`nonlocal` statement may prepend an assignment or augmented
    assignment, but not an expression.
index 54be1e1cec3bbe3b091d4262643f228a9ac36769..fee298deef6ec2067ae06a6e75a84d85b7261f32 100644 (file)
@@ -503,10 +503,12 @@ assert isinstance([], AppendableSequence)
 @abstractmethod decorator -- you can't instantiate classes w/
 an abstract method.
 
-@abstractproperty decorator
-@abstractproperty
-def readonly(self):
-   return self._x
+::
+
+    @abstractproperty decorator
+    @abstractproperty
+    def readonly(self):
+       return self._x
 
 
 .. seealso::
@@ -1163,7 +1165,7 @@ This section lists previously described changes, and a few
 esoteric bugfixes, that may require changes to your
 code:
 
-* The :method:`__init__` method of :class:`collections.deque`
+* The :meth:`__init__` method of :class:`collections.deque`
   now clears any existing contents of the deque
   before adding elements from the iterable.  This change makes the
   behavior match that of ``list.__init__()``.  
index d539683be1756d317bc9e93cfc8db9462e47cf81..504ae19549cce69804e280068a8df69ad0c0f4aa 100644 (file)
@@ -54,15 +54,23 @@ def namedtuple(typename, field_names, verbose=False):
         seen_names.add(name)
 
     # Create and fill-in the class template
+    numfields = len(field_names)
     argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
     reprtxt = ', '.join('%s=%%r' % name for name in field_names)
     dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
     template = '''class %(typename)s(tuple):
         '%(typename)s(%(argtxt)s)' \n
         __slots__ = () \n
+        _fields = %(field_names)r \n
         def __new__(cls, %(argtxt)s):
             return tuple.__new__(cls, (%(argtxt)s)) \n
-        _cast = classmethod(tuple.__new__) \n
+        @classmethod
+        def _make(cls, iterable):
+            'Make a new %(typename)s object from a sequence or iterable'
+            result = tuple.__new__(cls, iterable)
+            if len(result) != %(numfields)d:
+                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
+            return result \n
         def __repr__(self):
             return '%(typename)s(%(reprtxt)s)' %% self \n
         def _asdict(t):
@@ -70,10 +78,10 @@ def namedtuple(typename, field_names, verbose=False):
             return {%(dicttxt)s} \n
         def _replace(self, **kwds):
             'Return a new %(typename)s object replacing specified fields with new values'
-            return %(typename)s._cast(map(kwds.get, %(field_names)r, self)) \n
-        @property
-        def _fields(self):
-            return %(field_names)r \n\n''' % locals()
+            result = self._make(map(kwds.pop, %(field_names)r, self))
+            if kwds:
+                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
+            return result \n\n''' % locals()
     for i, name in enumerate(field_names):
         template += '        %s = property(itemgetter(%d))\n' % (name, i)
     if verbose:
index 06b2293293ee1cb179cb04aa50a8b4dcb2392d64..c4a4ac5f70593cea8307a3df1f52f2807bf28ada 100644 (file)
@@ -254,12 +254,10 @@ def walk(top, func, arg):
     except os.error:
         return
     func(arg, top, names)
-    exceptions = ('.', '..')
     for name in names:
-        if name not in exceptions:
-            name = join(top, name)
-            if isdir(name):
-                walk(name, func, arg)
+        name = join(top, name)
+        if isdir(name):
+            walk(name, func, arg)
 
 
 # Expand paths beginning with '~' or '~user'.
@@ -492,4 +490,6 @@ def relpath(path, start=curdir):
         i += 1
 
     rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
+    if not rel_list:
+        return curdir
     return join(*rel_list)
index 6d4a9e2111bd5d4631bc081f215266daa34a3745..ee6d0f2407ab8e09d8ba9cda0a1c404e4df3de0e 100644 (file)
@@ -178,8 +178,8 @@ def samestat(s1, s2):
 def ismount(path):
     """Test whether a path is a mount point"""
     try:
-        s1 = os.stat(path)
-        s2 = os.stat(join(path, '..'))
+        s1 = os.lstat(path)
+        s2 = os.lstat(join(path, '..'))
     except os.error:
         return False # It doesn't exist -- so not a mount point :-)
     dev1 = s1.st_dev
@@ -398,4 +398,6 @@ def relpath(path, start=curdir):
     i = len(commonprefix([start_list, path_list]))
 
     rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
+    if not rel_list:
+        return curdir
     return join(*rel_list)
index a21f1abbb7296d5dbbea954532ac7b264871f1e3..9ea92d0ebde91afcb06071173b353edd9c0d9427 100644 (file)
@@ -2021,11 +2021,11 @@ class TarFile(object):
 
         # Set correct owner, mtime and filemode on directories.
         for tarinfo in directories:
-            path = os.path.join(path, tarinfo.name)
+            dirpath = os.path.join(path, tarinfo.name)
             try:
-                self.chown(tarinfo, path)
-                self.utime(tarinfo, path)
-                self.chmod(tarinfo, path)
+                self.chown(tarinfo, dirpath)
+                self.utime(tarinfo, dirpath)
+                self.chmod(tarinfo, dirpath)
             except ExtractError as e:
                 if self.errorlevel > 1:
                     raise
index fdc82fc233f3f7c01e1c37a136435619325fde6c..d8cf72ee01b4a70df96e035592e2fe45441a40a1 100644 (file)
@@ -20,6 +20,7 @@ class TestNamedTuple(unittest.TestCase):
         self.assertEqual(Point.__slots__, ())
         self.assertEqual(Point.__module__, __name__)
         self.assertEqual(Point.__getitem__, tuple.__getitem__)
+        self.assertEqual(Point._fields, ('x', 'y'))
 
         self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi')       # type has non-alpha char
         self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi')      # type has keyword
@@ -34,6 +35,9 @@ class TestNamedTuple(unittest.TestCase):
         namedtuple('Point0', 'x1 y2')   # Verify that numbers are allowed in names
         namedtuple('_', 'a b c')        # Test leading underscores in a typename
 
+        self.assertRaises(TypeError, Point._make, [11])                     # catch too few args
+        self.assertRaises(TypeError, Point._make, [11, 22, 33])             # catch too many args
+
     def test_instance(self):
         Point = namedtuple('Point', 'x y')
         p = Point(11, 22)
@@ -49,18 +53,17 @@ class TestNamedTuple(unittest.TestCase):
         self.assertEqual(repr(p), 'Point(x=11, y=22)')
         self.assert_('__dict__' not in dir(p))                              # verify instance has no dict
         self.assert_('__weakref__' not in dir(p))
-        self.assertEqual(p, Point._cast([11, 22]))                          # test _cast classmethod
+        self.assertEqual(p, Point._make([11, 22]))                          # test _make classmethod
         self.assertEqual(p._fields, ('x', 'y'))                             # test _fields attribute
         self.assertEqual(p._replace(x=1), (1, 22))                          # test _replace method
         self.assertEqual(p._asdict(), dict(x=11, y=22))                     # test _asdict method
 
-        # Verify that _fields is read-only
         try:
-            p._fields = ('F1' ,'F2')
-        except AttributeError:
+            p._replace(x=1, error=2)
+        except ValueError:
             pass
         else:
-            self.fail('The _fields attribute needs to be read-only')
+            self._fail('Did not detect an incorrect fieldname')
 
         # verify that field string can have commas
         Point = namedtuple('Point', 'x, y')
@@ -94,14 +97,14 @@ class TestNamedTuple(unittest.TestCase):
     def test_odd_sizes(self):
         Zero = namedtuple('Zero', '')
         self.assertEqual(Zero(), ())
-        self.assertEqual(Zero._cast([]), ())
+        self.assertEqual(Zero._make([]), ())
         self.assertEqual(repr(Zero()), 'Zero()')
         self.assertEqual(Zero()._asdict(), {})
         self.assertEqual(Zero()._fields, ())
 
         Dot = namedtuple('Dot', 'd')
         self.assertEqual(Dot(1), (1,))
-        self.assertEqual(Dot._cast([1]), (1,))
+        self.assertEqual(Dot._make([1]), (1,))
         self.assertEqual(Dot(1).d, 1)
         self.assertEqual(repr(Dot(1)), 'Dot(d=1)')
         self.assertEqual(Dot(1)._asdict(), {'d':1})
@@ -115,7 +118,7 @@ class TestNamedTuple(unittest.TestCase):
         Big = namedtuple('Big', names)
         b = Big(*range(n))
         self.assertEqual(b, tuple(range(n)))
-        self.assertEqual(Big._cast(range(n)), tuple(range(n)))
+        self.assertEqual(Big._make(range(n)), tuple(range(n)))
         for pos, name in enumerate(names):
             self.assertEqual(getattr(b, name), pos)
         repr(b)                                 # make sure repr() doesn't blow-up
index 6ebfb695859540a370b7a35115d1b8e03ce9e44a..db370b11e12dadd98d557f7e68d1f9bfc89450dc 100644 (file)
@@ -909,7 +909,7 @@ Tests of `DocTestRunner`'s option flag handling.
 
 Several option flags can be used to customize the behavior of the test
 runner.  These are defined as module constants in doctest, and passed
-to the DocTestRunner constructor (multiple constants should be or-ed
+to the DocTestRunner constructor (multiple constants should be ORed
 together).
 
 The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
index c6dbf2e0785132193a8d5035d98a9416b85fe26c..3c05e637fba24a65543cc1ca6c14156b5627fed3 100644 (file)
@@ -166,6 +166,7 @@ tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
 tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
 tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
 tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
+tester('ntpath.relpath("a", "a")', '.')
 
 if errors:
     raise TestFailed(str(errors) + " errors.")
index 8c0d5ff7831f76f322e1e8f4eb340b6567028e69..a25e2b21597d7ad16565e16cc00d818785b37a38 100644 (file)
@@ -501,6 +501,7 @@ class PosixPathTest(unittest.TestCase):
             self.assertEqual(posixpath.relpath("a", "../b"), "../"+curdir+"/a")
             self.assertEqual(posixpath.relpath("a/b", "../c"), "../"+curdir+"/a/b")
             self.assertEqual(posixpath.relpath("a", "b/c"), "../../a")
+            self.assertEqual(posixpath.relpath("a", "a"), ".")
         finally:
             os.getcwd = real_getcwd
 
index 97445a079f908df49dfeab37de05402712c626d0..535f0ef81edf3be91d7bf12dcc33e78b3611eb68 100644 (file)
@@ -9,6 +9,8 @@ import time
 import thread, threading
 import Queue
 import sys
+import os
+import array
 from weakref import proxy
 import signal
 
@@ -508,6 +510,15 @@ class GeneralModuleTests(unittest.TestCase):
         self.assertEqual(sock.proto, 0)
         sock.close()
 
+    def test_sock_ioctl(self):
+        if os.name != "nt":
+            return
+        self.assert_(hasattr(socket.socket, 'ioctl'))
+        self.assert_(hasattr(socket, 'SIO_RCVALL'))
+        self.assert_(hasattr(socket, 'RCVALL_ON'))
+        self.assert_(hasattr(socket, 'RCVALL_OFF'))
+
+
 class BasicTCPTest(SocketConnectedTest):
 
     def __init__(self, methodName='runTest'):
index a97df37fd024770cc4fb103299d3f81b4ec8c6ac..91cf02469a9ee86c12b71cddd338f16159ad58e3 100644 (file)
@@ -243,6 +243,23 @@ class MiscReadTest(ReadTest):
         data = open(os.path.join(TEMPDIR, "ustar/symtype"), "rb").read()
         self.assertEqual(md5sum(data), md5_regtype)
 
+    def test_extractall(self):
+        # Test if extractall() correctly restores directory permissions
+        # and times (see issue1735).
+        if sys.platform == "win32":
+            # Win32 has no support for utime() on directories or
+            # fine grained permissions.
+            return
+
+        tar = tarfile.open(tarname, encoding="iso8859-1")
+        directories = [t for t in tar if t.isdir()]
+        tar.extractall(TEMPDIR, directories)
+        for tarinfo in directories:
+            path = os.path.join(TEMPDIR, tarinfo.name)
+            self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777)
+            self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
+        tar.close()
+
 
 class StreamReadTest(ReadTest):
 
index de08613846c34f63bed369fe2e5cc6270af5f72e..8ab8f35c2111be7d435ae1305617436b49fa1ccf 100644 (file)
@@ -254,6 +254,24 @@ class UrlParseTestCase(unittest.TestCase):
         self.assertEqual(p.port, 80)
         self.assertEqual(p.geturl(), url)
 
+        # Addressing issue1698, which suggests Username can contain
+        # "@" characters.  Though not RFC compliant, many ftp sites allow
+        # and request email addresses as usernames.
+
+        url = "http://User@example.com:Pass@www.python.org:080/doc/?query=yes#frag"
+        p = urlparse.urlsplit(url)
+        self.assertEqual(p.scheme, "http")
+        self.assertEqual(p.netloc, "User@example.com:Pass@www.python.org:080")
+        self.assertEqual(p.path, "/doc/")
+        self.assertEqual(p.query, "query=yes")
+        self.assertEqual(p.fragment, "frag")
+        self.assertEqual(p.username, "User@example.com")
+        self.assertEqual(p.password, "Pass")
+        self.assertEqual(p.hostname, "www.python.org")
+        self.assertEqual(p.port, 80)
+        self.assertEqual(p.geturl(), url)
+
+
     def test_attributes_bad_port(self):
         """Check handling of non-integer ports."""
         p = urlparse.urlsplit("http://www.example.net:foo")
@@ -287,6 +305,11 @@ class UrlParseTestCase(unittest.TestCase):
         self.assertEqual(p.port, None)
         self.assertEqual(p.geturl(), uri)
 
+    def test_noslash(self):
+        # Issue 1637: http://foo.com?query is legal
+        self.assertEqual(urlparse.urlparse("http://example.com?blahblah=/foo"),
+                         ('http', 'example.com', '', '', 'blahblah=/foo', ''))
+
 def test_main():
     test_support.run_unittest(UrlParseTestCase)
 
index 431771405dc813f9dfd6cac9130c796435cf0aa0..1f435b99c34bb623247bc93bb01012ba44eff7cf 100644 (file)
@@ -82,7 +82,7 @@ class BaseResult(tuple):
     def username(self):
         netloc = self.netloc
         if "@" in netloc:
-            userinfo = netloc.split("@", 1)[0]
+            userinfo = netloc.rsplit("@", 1)[0]
             if ":" in userinfo:
                 userinfo = userinfo.split(":", 1)[0]
             return userinfo
@@ -92,7 +92,7 @@ class BaseResult(tuple):
     def password(self):
         netloc = self.netloc
         if "@" in netloc:
-            userinfo = netloc.split("@", 1)[0]
+            userinfo = netloc.rsplit("@", 1)[0]
             if ":" in userinfo:
                 return userinfo.split(":", 1)[1]
         return None
@@ -101,7 +101,7 @@ class BaseResult(tuple):
     def hostname(self):
         netloc = self.netloc
         if "@" in netloc:
-            netloc = netloc.split("@", 1)[1]
+            netloc = netloc.rsplit("@", 1)[1]
         if ":" in netloc:
             netloc = netloc.split(":", 1)[0]
         return netloc.lower() or None
@@ -110,7 +110,7 @@ class BaseResult(tuple):
     def port(self):
         netloc = self.netloc
         if "@" in netloc:
-            netloc = netloc.split("@", 1)[1]
+            netloc = netloc.rsplit("@", 1)[1]
         if ":" in netloc:
             port = netloc.split(":", 1)[1]
             return int(port, 10)
@@ -169,13 +169,12 @@ def _splitparams(url):
     return url[:i], url[i+1:]
 
 def _splitnetloc(url, start=0):
-    for c in '/?#': # the order is important!
-        delim = url.find(c, start)
-        if delim >= 0:
-            break
-    else:
-        delim = len(url)
-    return url[start:delim], url[delim:]
+    delim = len(url)   # position of end of domain part of url, default is end
+    for c in '/?#':    # look for delimiters; the order is NOT important
+        wdelim = url.find(c, start)        # find first of this delim
+        if wdelim >= 0:                    # if found
+            delim = min(delim, wdelim)     # use earliest delim position
+    return url[start:delim], url[delim:]   # return (domain, rest)
 
 def urlsplit(url, scheme='', allow_fragments=True):
     """Parse a URL into 5 components:
index a4febfdab4121adf4eb41e326b69d4353f162da3..aafcf08bde7c6d13cf93abc19ba8850c0aae15ad 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -463,6 +463,7 @@ James A Morrison
 Sape Mullender
 Sjoerd Mullender
 Michael Muller
+John Nagle
 Takahiro Nakayama
 Travers Naran
 Fredrik Nehr
index 4361bfac6238a6d3180bef440441774460950f08..1539f21ff8b7f44391631573d02a54d8b06f8bc9 100644 (file)
@@ -378,7 +378,7 @@ following values:\n\
     LOCK_SH - acquire a shared lock\n\
     LOCK_EX - acquire an exclusive lock\n\
 \n\
-When operation is LOCK_SH or LOCK_EX, it can also be bit-wise OR'd with\n\
+When operation is LOCK_SH or LOCK_EX, it can also be bitwise ORed with\n\
 LOCK_NB to avoid blocking on lock acquisition.  If LOCK_NB is used and the\n\
 lock cannot be acquired, an IOError will be raised and the exception will\n\
 have an errno attribute set to EACCES or EAGAIN (depending on the operating\n\
index 3909cbc9763908f28d18d70030dcb4f94542ab52..b59c15dc515b05c60d1ba7fe4f3e690a5430853f 100644 (file)
@@ -2510,6 +2510,31 @@ PyDoc_STRVAR(shutdown_doc,
 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
 
+#ifdef MS_WINDOWS
+static PyObject*
+sock_ioctl(PySocketSockObject *s, PyObject *arg)
+{
+       unsigned long cmd = SIO_RCVALL;
+       unsigned int option = RCVALL_ON;
+        DWORD recv;
+
+       if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
+               return NULL;
+
+       if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), 
+                    NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
+               return set_error();
+       }
+       return PyLong_FromUnsignedLong(recv);
+}
+PyDoc_STRVAR(sock_ioctl_doc,
+"ioctl(cmd, option) -> long\n\
+\n\
+Control the socket with WSAIoctl syscall. Currently only socket.SIO_RCVALL\n\
+is supported as control. Options must be one of the socket.RCVALL_*\n\
+constants.");
+
+#endif
 
 /* List of methods for socket objects */
 
@@ -2534,6 +2559,10 @@ static PyMethodDef sock_methods[] = {
                          METH_NOARGS, getsockname_doc},
        {"getsockopt",    (PyCFunction)sock_getsockopt, METH_VARARGS,
                          getsockopt_doc},
+#ifdef MS_WINDOWS
+       {"ioctl",         (PyCFunction)sock_ioctl, METH_VARARGS,
+                         sock_ioctl_doc},
+#endif
        {"listen",        (PyCFunction)sock_listen, METH_O,
                          listen_doc},
        {"recv",          (PyCFunction)sock_recv, METH_VARARGS,
@@ -3957,7 +3986,7 @@ See the socket module for documentation.");
 PyMODINIT_FUNC
 init_socket(void)
 {
-       PyObject *m, *has_ipv6;
+       PyObject *m, *has_ipv6, *tmp;
 
        if (!os_init())
                return;
@@ -4794,6 +4823,18 @@ init_socket(void)
        PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
 #endif
 
+#ifdef SIO_RCVALL
+       tmp = PyLong_FromUnsignedLong(SIO_RCVALL);
+       if (tmp == NULL)
+               return;
+       PyModule_AddObject(m, "SIO_RCVALL", tmp);
+       PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
+       PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
+       PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
+       PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
+       PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
+#endif /* _MSTCPIP_ */
+
        /* Initialize gethostbyname lock */
 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
        netdb_lock = PyThread_allocate_lock();
index 1df1ae62b9e962822aecb91a972d8f66a1a3aa80..43c95fd5f664d308db03ded97aa856f92c6fa320 100644 (file)
@@ -16,6 +16,7 @@
 #if _MSC_VER >= 1300
 # include <winsock2.h>
 # include <ws2tcpip.h>
+# include <MSTcpIP.h> /* for SIO_RCVALL */
 # define HAVE_ADDRINFO
 # define HAVE_SOCKADDR_STORAGE
 # define HAVE_GETADDRINFO
index dada3865f9e5088c6c7d44fa7a4b10812ba39ab6..a7205d00d33ef257d30e1c008643be6b49dcd0c6 100644 (file)
@@ -24,7 +24,9 @@ else:
 ROOT = os.path.abspath(os.path.join(here, par, par))
 # Windows 2000 compatibility: WINVER 0x0500
 # http://msdn2.microsoft.com/en-us/library/aa383745.aspx
-NMAKE = "nmake /nologo /f %s COMPILERFLAGS=-DWINVER=0x0500 %s %s"
+NMAKE = ('nmake /nologo /f %s '
+    'COMPILERFLAGS=\"-DWINVER=0x0500 -D_WIN32_WINNT=0x0500 -DNTDDI_VERSION=NTDDI_WIN2KSP4\"'
+    '%s %s')
 
 def nmake(makefile, command="", **kw):
     defines = ' '.join(k+'='+v for k, v in kw.items())
index 2b9e0bee3765c922e425fbc6ae76d3ef497286b9..39c091b39a819654be3241c5a8f1ab6629e5e1b6 100644 (file)
@@ -1,12 +1,13 @@
 
 /* Support for dynamic loading of extension modules */
 
+#include "Python.h"
+
 #ifdef HAVE_DIRECT_H
 #include <direct.h>
 #endif
 #include <ctype.h>
 
-#include "Python.h"
 #include "importdl.h"
 #include <windows.h>
 
index 6c19b45fd260070591307da151e8ab0639b7b8f8..14fb84ba715b8c5e9d59cfe7fc871316ce10e9d3 100644 (file)
@@ -48,6 +48,8 @@ PyOS_ascii_strtod(const char *nptr, char **endptr)
        size_t decimal_point_len;
        const char *p, *decimal_point_pos;
        const char *end = NULL; /* Silence gcc */
+       const char *digits_pos = NULL;
+       int negate = 0;
 
        assert(nptr != NULL);
 
@@ -60,18 +62,41 @@ PyOS_ascii_strtod(const char *nptr, char **endptr)
        assert(decimal_point_len != 0);
 
        decimal_point_pos = NULL;
+
+       /* We process any leading whitespace and the optional sign manually,
+          then pass the remainder to the system strtod.  This ensures that
+          the result of an underflow has the correct sign. (bug #1725)  */
+
+       p = nptr;
+       /* Skip leading space */
+       while (ISSPACE(*p))
+               p++;
+
+       /* Process leading sign, if present */
+       if (*p == '-') {
+               negate = 1;
+               p++;
+       } else if (*p == '+') {
+               p++;
+       }
+
+       /* What's left should begin with a digit, a decimal point, or one of
+          the letters i, I, n, N. It should not begin with 0x or 0X */
+       if ((!ISDIGIT(*p) &&
+            *p != '.' && *p != 'i' && *p != 'I' && *p != 'n' && *p != 'N')
+           ||
+           (*p == '0' && (p[1] == 'x' || p[1] == 'X')))
+       {
+               if (endptr)
+                       *endptr = (char*)nptr;
+               errno = EINVAL;
+               return val;
+       }
+       digits_pos = p;
+
        if (decimal_point[0] != '.' || 
            decimal_point[1] != 0)
        {
-               p = nptr;
-                 /* Skip leading space */
-               while (ISSPACE(*p))
-                       p++;
-
-                 /* Skip leading optional sign */
-               if (*p == '+' || *p == '-')
-                       p++;
-
                while (ISDIGIT(*p))
                        p++;
 
@@ -93,7 +118,8 @@ PyOS_ascii_strtod(const char *nptr, char **endptr)
                else if (strncmp(p, decimal_point, decimal_point_len) == 0)
                {
                        /* Python bug #1417699 */
-                       *endptr = (char*)nptr;
+                       if (endptr)
+                               *endptr = (char*)nptr;
                        errno = EINVAL;
                        return val;
                }
@@ -109,7 +135,8 @@ PyOS_ascii_strtod(const char *nptr, char **endptr)
                char *copy, *c;
 
                /* We need to convert the '.' to the locale specific decimal point */
-               copy = (char *)PyMem_MALLOC(end - nptr + 1 + decimal_point_len);
+               copy = (char *)PyMem_MALLOC(end - digits_pos +
+                                           1 + decimal_point_len);
                if (copy == NULL) {
                        if (endptr)
                                *endptr = (char *)nptr;
@@ -118,8 +145,8 @@ PyOS_ascii_strtod(const char *nptr, char **endptr)
                }
 
                c = copy;
-               memcpy(c, nptr, decimal_point_pos - nptr);
-               c += decimal_point_pos - nptr;
+               memcpy(c, digits_pos, decimal_point_pos - digits_pos);
+               c += decimal_point_pos - digits_pos;
                memcpy(c, decimal_point, decimal_point_len);
                c += decimal_point_len;
                memcpy(c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
@@ -131,24 +158,27 @@ PyOS_ascii_strtod(const char *nptr, char **endptr)
                if (fail_pos)
                {
                        if (fail_pos > decimal_point_pos)
-                               fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
+                               fail_pos = (char *)digits_pos +
+                                       (fail_pos - copy) -
+                                       (decimal_point_len - 1);
                        else
-                               fail_pos = (char *)nptr + (fail_pos - copy);
+                               fail_pos = (char *)digits_pos +
+                                       (fail_pos - copy);
                }
 
                PyMem_FREE(copy);
 
        }
        else {
-               unsigned i = 0;
-               if (nptr[i] == '-')
-                       i++;
-               if (nptr[i] == '0' && (nptr[i+1] == 'x' || nptr[i+1] == 'X'))
-                       fail_pos = (char*)nptr;
-               else
-                       val = strtod(nptr, &fail_pos);
+               val = strtod(digits_pos, &fail_pos);
        }
 
+       if (fail_pos == digits_pos)
+               fail_pos = (char *)nptr;
+
+       if (negate && fail_pos != nptr)
+               val = -val;
+
        if (endptr)
                *endptr = fail_pos;
 
index c0537b4c0686ac02a2d77643560dd11a729a5bb1..54101931c2ab718e5d1261cbb6a7a0d165eafd0f 100644 (file)
@@ -4,12 +4,12 @@ cmd /c Tools\buildbot\external.bat
 @rem build release versions of things
 call "%VS90COMNTOOLS%vsvars32.bat"
 if not exist ..\db-4.4.20\build_win32\release\libdb44s.lib (
-   devenv ..\db-4.4.20\build_win32\Berkeley_DB.sln /build Release /project db_static
+  vcbuild db-4.4.20\build_win32\Berkeley_DB.sln /build Release /project db_static
 )
 
 @rem build Python
 cmd /q/c Tools\buildbot\kill_python.bat
-devenv.com /useenv /build Release PCbuild\pcbuild.sln
+vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32"
 
 @rem build the documentation
 bash.exe -c 'cd Doc;make PYTHON=python2.5 update htmlhelp'
index bedfade99a05c3fbec797e822b57a1bcb7e67957..d39e21c2fed4492a80f6dfed1defb3857b3c4ec3 100644 (file)
@@ -27,11 +27,10 @@ have_tcl = True
 # Where is sqlite3.dll located, relative to srcdir?
 sqlite_dir = "../sqlite-source-3.3.4"
 # path to PCbuild directory
-PCBUILD="PC\\VS7.1"
-#PCBUILD="PCbuild"
+PCBUILD="PCbuild"
 # msvcrt version
-MSVCR = "71"
-#MSVCR = "90"
+#MSVCR = "71"
+MSVCR = "90"
 
 try:
     from config import *
@@ -904,12 +903,15 @@ def add_files(db):
                     language=installer.FileVersion(pydllsrc, 1))
     # XXX determine dependencies
     if MSVCR == "90":
-        version, lang = extract_msvcr90()
-        dlldir.start_component("msvcr90", flags=8, keyfile="msvcr90.dll",
-                               uuid=msvcr90_uuid)
-        dlldir.add_file("msvcr90.dll", src=os.path.abspath("msvcr90.dll"),
-                        version=version, language=lang)
-        tmpfiles.append("msvcr90.dll")
+        # XXX don't package the CRT for the moment;
+        # this should probably use the merge module in the long run.
+        pass
+        #version, lang = extract_msvcr90()
+        #dlldir.start_component("msvcr90", flags=8, keyfile="msvcr90.dll",
+        #                       uuid=msvcr90_uuid)
+        #dlldir.add_file("msvcr90.dll", src=os.path.abspath("msvcr90.dll"),
+        #                version=version, language=lang)
+        #tmpfiles.append("msvcr90.dll")
     else:
         version, lang = extract_msvcr71()
         dlldir.start_component("msvcr71", flags=8, keyfile="msvcr71.dll",