Merged revisions 55817-55961 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/branches/p3yk

................
  r55837 | guido.van.rossum | 2007-06-08 16:04:42 -0700 (Fri, 08 Jun 2007) | 2 lines

  PEP 3119 -- the abc module.
................
  r55838 | guido.van.rossum | 2007-06-08 17:38:55 -0700 (Fri, 08 Jun 2007) | 2 lines

  Implement part of PEP 3119 -- One Trick Ponies.
................
  r55847 | guido.van.rossum | 2007-06-09 08:28:06 -0700 (Sat, 09 Jun 2007) | 2 lines

  Different way to do one trick ponies, allowing registration (per PEP strawman).
................
  r55849 | guido.van.rossum | 2007-06-09 18:06:38 -0700 (Sat, 09 Jun 2007) | 3 lines

  Make sure that the magic looking for __hash__ (etc.) doesn't apply to
  real subclasses of Hashable.
................
  r55852 | guido.van.rossum | 2007-06-10 08:29:51 -0700 (Sun, 10 Jun 2007) | 2 lines

  Add some more examples, e.g. generators and dict views.
................
  r55853 | guido.van.rossum | 2007-06-10 08:31:59 -0700 (Sun, 10 Jun 2007) | 2 lines

  keys() and items() *are* containers -- just values() isn't.
................
  r55864 | georg.brandl | 2007-06-10 15:29:40 -0700 (Sun, 10 Jun 2007) | 2 lines

  PEP 3127: new octal literals, binary literals.
................
  r55865 | georg.brandl | 2007-06-10 15:31:37 -0700 (Sun, 10 Jun 2007) | 2 lines

  Some octal literal fixes in Tools.
................
  r55866 | georg.brandl | 2007-06-10 15:37:43 -0700 (Sun, 10 Jun 2007) | 2 lines

  Tokenizer changes for PEP 3127.
................
  r55867 | georg.brandl | 2007-06-10 15:37:55 -0700 (Sun, 10 Jun 2007) | 2 lines

  Some docs for PEP 3127.
................
  r55868 | georg.brandl | 2007-06-10 15:44:39 -0700 (Sun, 10 Jun 2007) | 2 lines

  Missed a place in intobject.c. Is that used anymore anyway?
................
  r55871 | neal.norwitz | 2007-06-10 18:31:49 -0700 (Sun, 10 Jun 2007) | 182 lines

  Merged revisions 55729-55868 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r55731 | neal.norwitz | 2007-06-01 00:29:12 -0700 (Fri, 01 Jun 2007) | 7 lines

    SF 1668596/1720897: distutils now copies data files
    even if package_dir is empty.

    This needs to be backported.  I'm too tired tonight.  It would be great
    if someone backports this if the buildbots are ok with it.  Otherwise,
    I will try to get to it tomorrow.
  ........
    r55732 | georg.brandl | 2007-06-01 04:33:33 -0700 (Fri, 01 Jun 2007) | 2 lines

    Bug #1722484: remove docstrings again when running with -OO.
  ........
    r55735 | georg.brandl | 2007-06-01 12:20:27 -0700 (Fri, 01 Jun 2007) | 2 lines

    Fix wrong issue number.
  ........
    r55739 | brett.cannon | 2007-06-01 20:02:29 -0700 (Fri, 01 Jun 2007) | 3 lines

    Have configure raise an error when building on AtheOS.  Code specific to AtheOS
    will be removed in Python 2.7.
  ........
    r55746 | neal.norwitz | 2007-06-02 11:33:53 -0700 (Sat, 02 Jun 2007) | 1 line

    Update expected birthday of 2.6
  ........
    r55751 | neal.norwitz | 2007-06-03 13:32:50 -0700 (Sun, 03 Jun 2007) | 10 lines

    Backout the original 'fix' to 1721309 which had no effect.
    Different versions of Berkeley DB handle this differently.
    The comments and bug report should have the details.  Memory is allocated
    in 4.4 (and presumably earlier), but not in 4.5.  Thus
    4.5 has the free error, but not earlier versions.

    Mostly update comments, plus make the free conditional.

    This fix was already applied to the 2.5 branch.
  ........
    r55752 | brett.cannon | 2007-06-03 16:13:41 -0700 (Sun, 03 Jun 2007) | 6 lines

    Make _strptime.TimeRE().pattern() use ``\s+`` for matching whitespace instead
    of ``\s*``.  This prevents patterns from "stealing" bits from other patterns in
    order to make a match work.

    Closes bug #1730389.  Will be backported.
  ........
    r55766 | hyeshik.chang | 2007-06-05 11:16:52 -0700 (Tue, 05 Jun 2007) | 4 lines

    Fix build on FreeBSD.  Bluetooth HCI API in FreeBSD is quite different
    from Linux's.  Just fix the build for now but the code doesn't
    support the complete capability of HCI on FreeBSD yet.
  ........
    r55770 | hyeshik.chang | 2007-06-05 11:58:51 -0700 (Tue, 05 Jun 2007) | 4 lines

    Bug #1728403: Fix a bug that CJKCodecs StreamReader hangs when it
    reads a file that ends with incomplete sequence and sizehint argument
    for .read() is specified.
  ........
    r55775 | hyeshik.chang | 2007-06-05 12:28:15 -0700 (Tue, 05 Jun 2007) | 2 lines

    Fix for Windows: close a temporary file before trying to delete it.
  ........
    r55783 | guido.van.rossum | 2007-06-05 14:24:47 -0700 (Tue, 05 Jun 2007) | 2 lines

    Patch by Tim Delany (missing DECREF). SF #1731330.
  ........
    r55785 | collin.winter | 2007-06-05 17:17:35 -0700 (Tue, 05 Jun 2007) | 3 lines

    Patch #1731049: make threading.py use a proper "raise" when checking internal state, rather than assert statements (which get stripped out by -O).
  ........
    r55786 | facundo.batista | 2007-06-06 08:13:37 -0700 (Wed, 06 Jun 2007) | 4 lines


    FTP.ntransfercmd method now uses create_connection when passive,
    using the timeout received in connection time.
  ........
    r55792 | facundo.batista | 2007-06-06 10:15:23 -0700 (Wed, 06 Jun 2007) | 7 lines


    Added an optional timeout parameter to function urllib2.urlopen,
    with tests in test_urllib2net.py (must have network resource
    enabled to execute them). Also modified test_urllib2.py because
    testing mock classes must take it into acount. Docs are also
    updated.
  ........
    r55793 | thomas.heller | 2007-06-06 13:19:19 -0700 (Wed, 06 Jun 2007) | 1 line

    Build _ctypes and _ctypes_test in the ReleaseAMD64 configuration.
  ........
    r55802 | georg.brandl | 2007-06-07 06:23:24 -0700 (Thu, 07 Jun 2007) | 3 lines

    Disallow function calls like foo(None=1).
    Backport from py3k rev. 55708 by Guido.
  ........
    r55804 | georg.brandl | 2007-06-07 06:30:24 -0700 (Thu, 07 Jun 2007) | 2 lines

    Make reindent.py executable.
  ........
    r55805 | georg.brandl | 2007-06-07 06:34:10 -0700 (Thu, 07 Jun 2007) | 2 lines

    Patch #1667860: Fix UnboundLocalError in urllib2.
  ........
    r55821 | kristjan.jonsson | 2007-06-07 16:53:49 -0700 (Thu, 07 Jun 2007) | 1 line

    Fixing changes to getbuildinfo.c that broke linux builds
  ........
    r55828 | thomas.heller | 2007-06-08 09:10:27 -0700 (Fri, 08 Jun 2007) | 1 line

    Make this test work with older Python releases where struct has no 't' format character.
  ........
    r55829 | martin.v.loewis | 2007-06-08 10:29:20 -0700 (Fri, 08 Jun 2007) | 3 lines

    Bug #1733488: Fix compilation of bufferobject.c on AIX.
    Will backport to 2.5.
  ........
    r55831 | thomas.heller | 2007-06-08 11:20:09 -0700 (Fri, 08 Jun 2007) | 2 lines

    [ 1715718 ] x64 clean compile patch for _ctypes, by Kristj?n Valur
    with small modifications.
  ........
    r55832 | thomas.heller | 2007-06-08 12:01:06 -0700 (Fri, 08 Jun 2007) | 1 line

    Fix gcc warnings intruduced by passing Py_ssize_t to PyErr_Format calls.
  ........
    r55833 | thomas.heller | 2007-06-08 12:08:31 -0700 (Fri, 08 Jun 2007) | 2 lines

    Fix wrong documentation, and correct the punktuation.
    Closes [1700455].
  ........
    r55834 | thomas.heller | 2007-06-08 12:14:23 -0700 (Fri, 08 Jun 2007) | 1 line

    Fix warnings by using proper function prototype.
  ........
    r55839 | neal.norwitz | 2007-06-08 20:36:34 -0700 (Fri, 08 Jun 2007) | 7 lines

    Prevent expandtabs() on string and unicode objects from causing a segfault when
    a large width is passed on 32-bit platforms.  Found by Google.

    It would be good for people to review this especially carefully and verify
    I don't have an off by one error and there is no other way to cause overflow.
  ........
    r55841 | neal.norwitz | 2007-06-08 21:48:22 -0700 (Fri, 08 Jun 2007) | 1 line

    Use macro version of GET_SIZE to avoid Coverity warning (#150) about a possible error.
  ........
    r55842 | martin.v.loewis | 2007-06-09 00:42:52 -0700 (Sat, 09 Jun 2007) | 3 lines

    Patch #1733960: Allow T_LONGLONG to accept ints.
    Will backport to 2.5.
  ........
    r55843 | martin.v.loewis | 2007-06-09 00:58:05 -0700 (Sat, 09 Jun 2007) | 2 lines

    Fix Windows build.
  ........
    r55845 | martin.v.loewis | 2007-06-09 03:10:26 -0700 (Sat, 09 Jun 2007) | 2 lines

    Provide LLONG_MAX for S390.
  ........
    r55854 | thomas.heller | 2007-06-10 08:59:17 -0700 (Sun, 10 Jun 2007) | 4 lines


    First version of build scripts for Windows/AMD64 (no external
    components are built yet, and 'kill_python' is disabled).
  ........
    r55855 | thomas.heller | 2007-06-10 10:55:51 -0700 (Sun, 10 Jun 2007) | 3 lines

    For now, disable the _bsddb, _sqlite3, _ssl, _testcapi, _tkinter
    modules in the ReleaseAMD64 configuration because they do not compile.
  ........
    r55856 | thomas.heller | 2007-06-10 11:27:54 -0700 (Sun, 10 Jun 2007) | 1 line

    Need to set the environment variables, otherwise devenv.com is not found.
  ........
    r55860 | thomas.heller | 2007-06-10 14:01:17 -0700 (Sun, 10 Jun 2007) | 1 line

    Revert commit 55855.
  ........
................
  r55880 | neal.norwitz | 2007-06-10 22:07:36 -0700 (Sun, 10 Jun 2007) | 5 lines

  Fix the refleak counter on test_collections.  The ABC metaclass creates
  a registry which must be cleared on each run.  Otherwise, there *seem*
  to be refleaks when there really aren't any.  (The class is held within
  the registry even though it's no longer needed.)
................
  r55884 | neal.norwitz | 2007-06-10 22:46:33 -0700 (Sun, 10 Jun 2007) | 1 line

  These tests have been removed, so they are no longer needed here
................
  r55886 | georg.brandl | 2007-06-11 00:26:37 -0700 (Mon, 11 Jun 2007) | 3 lines

  Optimize access to True and False in the compiler (if True)
  and the peepholer (LOAD_NAME True).
................
  r55905 | georg.brandl | 2007-06-11 10:02:26 -0700 (Mon, 11 Jun 2007) | 5 lines

  Remove __oct__ and __hex__ and use __index__ for converting
  non-ints before formatting in a base.

  Add a bin() builtin.
................
  r55906 | georg.brandl | 2007-06-11 10:04:44 -0700 (Mon, 11 Jun 2007) | 2 lines

  int(x, 0) does not "guess".
................
  r55907 | georg.brandl | 2007-06-11 10:05:47 -0700 (Mon, 11 Jun 2007) | 2 lines

  Add a comment to explain that nb_oct and nb_hex are nonfunctional.
................
  r55908 | guido.van.rossum | 2007-06-11 10:49:18 -0700 (Mon, 11 Jun 2007) | 2 lines

  Get rid of unused imports and comment.
................
  r55910 | guido.van.rossum | 2007-06-11 13:05:17 -0700 (Mon, 11 Jun 2007) | 2 lines

  _Abstract.__new__ now requires either no arguments or __init__ overridden.
................
  r55911 | guido.van.rossum | 2007-06-11 13:07:49 -0700 (Mon, 11 Jun 2007) | 7 lines

  Move the collections ABCs to a separate file, _abcoll.py, in order to avoid
  needing to import _collections.so during the bootstrap (this will become
  apparent in the next submit of os.py).

  Add (plain and mutable) ABCs for Set, Mapping, Sequence.
................
  r55912 | guido.van.rossum | 2007-06-11 13:09:31 -0700 (Mon, 11 Jun 2007) | 2 lines

  Rewrite the _Environ class to use the new collections ABCs.
................
  r55913 | guido.van.rossum | 2007-06-11 13:59:45 -0700 (Mon, 11 Jun 2007) | 72 lines

  Merged revisions 55869-55912 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r55869 | neal.norwitz | 2007-06-10 17:42:11 -0700 (Sun, 10 Jun 2007) | 1 line

    Add Atul Varma for patch # 1667860
  ........
    r55870 | neal.norwitz | 2007-06-10 18:22:03 -0700 (Sun, 10 Jun 2007) | 1 line

    Ignore valgrind problems on Ubuntu from ld
  ........
    r55872 | neal.norwitz | 2007-06-10 18:48:46 -0700 (Sun, 10 Jun 2007) | 2 lines

    Ignore config.status.lineno which seems new (new autoconf?)
  ........
    r55873 | neal.norwitz | 2007-06-10 19:14:39 -0700 (Sun, 10 Jun 2007) | 1 line

    Prevent these tests from running on Win64 since they don\'t apply there either
  ........
    r55874 | neal.norwitz | 2007-06-10 19:16:10 -0700 (Sun, 10 Jun 2007) | 5 lines

    Fix a bug when there was a newline in the string expandtabs was called on.
    This also catches another condition that can overflow.

    Will backport.
  ........
    r55879 | neal.norwitz | 2007-06-10 21:52:37 -0700 (Sun, 10 Jun 2007) | 1 line

    Prevent hang if the port cannot be opened.
  ........
    r55881 | neal.norwitz | 2007-06-10 22:28:45 -0700 (Sun, 10 Jun 2007) | 4 lines

    Add all of the distuils modules that don't seem to have explicit tests. :-(
    Move an import in mworkscompiler so that this module can be imported on
    any platform.  Hopefully this works on all platforms.
  ........
    r55882 | neal.norwitz | 2007-06-10 22:35:10 -0700 (Sun, 10 Jun 2007) | 4 lines

    SF #1734732, lower case the module names per PEP 8.

    Will backport.
  ........
    r55885 | neal.norwitz | 2007-06-10 23:16:48 -0700 (Sun, 10 Jun 2007) | 4 lines

    Not sure why this only fails sometimes on Unix machines. Better
    to disable it and only import msvccompiler on Windows since that's
    the only place it can work anyways.
  ........
    r55887 | neal.norwitz | 2007-06-11 00:29:43 -0700 (Mon, 11 Jun 2007) | 4 lines

    Bug #1734723: Fix repr.Repr() so it doesn't ignore the maxtuple attribute.

    Will backport
  ........
    r55889 | neal.norwitz | 2007-06-11 00:36:24 -0700 (Mon, 11 Jun 2007) | 1 line

    Reflow long line
  ........
    r55896 | thomas.heller | 2007-06-11 08:58:33 -0700 (Mon, 11 Jun 2007) | 3 lines

    Use "O&" in calls to PyArg_Parse when we need a 'void*' instead of "k"
    or "K" codes.
  ........
    r55901 | facundo.batista | 2007-06-11 09:27:08 -0700 (Mon, 11 Jun 2007) | 5 lines


    Added versionchanged flag to all the methods which received
    a new optional timeout parameter, and a versionadded flag to
    the socket.create_connection function.
  ........
................
  r55914 | guido.van.rossum | 2007-06-11 14:19:50 -0700 (Mon, 11 Jun 2007) | 3 lines

  New super() implementation, for PEP 3135 (though the PEP is not yet updated
  to this design, and small tweaks may still be made later).
................
  r55923 | guido.van.rossum | 2007-06-11 21:15:24 -0700 (Mon, 11 Jun 2007) | 4 lines

  I'm guessing this module broke when Neal ripped out the types module --
  it used 'list' both as a local variable and as the built-in list type.
  Renamed the local variable since that was easier.
................
  r55924 | guido.van.rossum | 2007-06-11 21:20:05 -0700 (Mon, 11 Jun 2007) | 5 lines

  Change all occurrences of super(<thisclass>, <firstarg>) to super().
  Seems to have worked, all the tests still pass.
  Exception: test_descr and test_descrtut, which have tons of these
  and are there to test the various usages.
................
  r55939 | collin.winter | 2007-06-12 13:57:33 -0700 (Tue, 12 Jun 2007) | 1 line

  Patch #1735485: remove StandardError from the exception hierarchy.
................
  r55954 | neal.norwitz | 2007-06-12 21:56:32 -0700 (Tue, 12 Jun 2007) | 51 lines

  Merged revisions 55913-55950 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r55926 | marc-andre.lemburg | 2007-06-12 02:09:58 -0700 (Tue, 12 Jun 2007) | 3 lines

    Apply patch #1734945 to support TurboLinux as distribution.
  ........
    r55927 | marc-andre.lemburg | 2007-06-12 02:26:49 -0700 (Tue, 12 Jun 2007) | 3 lines

    Add patch #1726668: Windows Vista support.
  ........
    r55929 | thomas.heller | 2007-06-12 08:36:22 -0700 (Tue, 12 Jun 2007) | 1 line

    Checkout, but do not yet try to build, exernal sources.
  ........
    r55930 | thomas.heller | 2007-06-12 09:08:27 -0700 (Tue, 12 Jun 2007) | 6 lines

    Add bufferoverflowU.lib to the libraries needed by _ssl (is this the
    right thing to do?).

    Set the /XP64 /RETAIL build enviroment in the makefile when building
    ReleaseAMD64.
  ........
    r55931 | thomas.heller | 2007-06-12 09:23:19 -0700 (Tue, 12 Jun 2007) | 5 lines

    Revert this change, since it breaks the win32 build:

    Add bufferoverflowU.lib to the libraries needed by _ssl (is this the
    right thing to do?).
  ........
    r55934 | thomas.heller | 2007-06-12 10:28:31 -0700 (Tue, 12 Jun 2007) | 3 lines

    Specify the bufferoverflowU.lib to the makefile on the command line
    (for ReleaseAMD64 builds).
  ........
    r55937 | thomas.heller | 2007-06-12 12:02:59 -0700 (Tue, 12 Jun 2007) | 3 lines

    Add bufferoverflowU.lib to PCBuild\_bsddb.vcproj.
    Build sqlite3.dll and bsddb.
  ........
    r55938 | thomas.heller | 2007-06-12 12:56:12 -0700 (Tue, 12 Jun 2007) | 2 lines

    Don't rebuild Berkeley DB if not needed (this was committed by accident).
  ........
    r55948 | martin.v.loewis | 2007-06-12 20:42:19 -0700 (Tue, 12 Jun 2007) | 3 lines

    Provide PY_LLONG_MAX on all systems having long long.
    Will backport to 2.5.
  ........
................
  r55959 | guido.van.rossum | 2007-06-13 09:22:41 -0700 (Wed, 13 Jun 2007) | 2 lines

  Fix a compilation warning.
................
This commit is contained in:
Guido van Rossum 2007-06-13 18:07:49 +00:00
parent 6374bb5a69
commit cd16bf6404
195 changed files with 3365 additions and 1472 deletions

View File

@ -381,7 +381,6 @@ completeness, here are all the variables:
\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes} \begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
\lineiii{PyExc_BaseException\ttindex{PyExc_BaseException}}{\exception{BaseException}}{(1), (4)} \lineiii{PyExc_BaseException\ttindex{PyExc_BaseException}}{\exception{BaseException}}{(1), (4)}
\lineiii{PyExc_Exception\ttindex{PyExc_Exception}}{\exception{Exception}}{(1)} \lineiii{PyExc_Exception\ttindex{PyExc_Exception}}{\exception{Exception}}{(1)}
\lineiii{PyExc_StandardError\ttindex{PyExc_StandardError}}{\exception{StandardError}}{(1)}
\lineiii{PyExc_ArithmeticError\ttindex{PyExc_ArithmeticError}}{\exception{ArithmeticError}}{(1)} \lineiii{PyExc_ArithmeticError\ttindex{PyExc_ArithmeticError}}{\exception{ArithmeticError}}{(1)}
\lineiii{PyExc_LookupError\ttindex{PyExc_LookupError}}{\exception{LookupError}}{(1)} \lineiii{PyExc_LookupError\ttindex{PyExc_LookupError}}{\exception{LookupError}}{(1)}
\lineiii{PyExc_AssertionError\ttindex{PyExc_AssertionError}}{\exception{AssertionError}}{} \lineiii{PyExc_AssertionError\ttindex{PyExc_AssertionError}}{\exception{AssertionError}}{}

View File

@ -437,8 +437,8 @@ You should be careful, however, not to pass them to functions
expecting pointers to mutable memory. If you need mutable memory expecting pointers to mutable memory. If you need mutable memory
blocks, ctypes has a \code{create{\_}string{\_}buffer} function which creates blocks, ctypes has a \code{create{\_}string{\_}buffer} function which creates
these in various ways. The current memory block contents can be these in various ways. The current memory block contents can be
accessed (or changed) with the \code{raw} property, if you want to access accessed (or changed) with the \code{raw} property; if you want to access
it as NUL terminated string, use the \code{string} property: it as NUL terminated string, use the \code{value} property:
\begin{verbatim} \begin{verbatim}
>>> from ctypes import * >>> from ctypes import *
>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes

View File

@ -845,7 +845,7 @@ exception is raised upon encountering the condition.
The following table summarizes the hierarchy of signals: The following table summarizes the hierarchy of signals:
\begin{verbatim} \begin{verbatim}
exceptions.ArithmeticError(exceptions.StandardError) exceptions.ArithmeticError(exceptions.Exception)
DecimalException DecimalException
Clamped Clamped
DivisionByZero(DecimalException, exceptions.ZeroDivisionError) DivisionByZero(DecimalException, exceptions.ZeroDivisionError)

View File

@ -64,13 +64,6 @@ from this class.
\versionchanged[Changed to inherit from \exception{BaseException}]{2.5} \versionchanged[Changed to inherit from \exception{BaseException}]{2.5}
\end{excdesc} \end{excdesc}
\begin{excdesc}{StandardError}
The base class for all built-in exceptions except
\exception{StopIteration}, \exception{GeneratorExit},
\exception{KeyboardInterrupt} and \exception{SystemExit}.
\exception{StandardError} itself is derived from \exception{Exception}.
\end{excdesc}
\begin{excdesc}{ArithmeticError} \begin{excdesc}{ArithmeticError}
The base class for those built-in exceptions that are raised for The base class for those built-in exceptions that are raised for
various arithmetic errors: \exception{OverflowError}, various arithmetic errors: \exception{OverflowError},
@ -143,9 +136,9 @@ Raised when an \keyword{assert} statement fails.
\begin{excdesc}{GeneratorExit} \begin{excdesc}{GeneratorExit}
Raise when a generator's \method{close()} method is called. Raise when a generator's \method{close()} method is called.
It directly inherits from \exception{Exception} instead of
\exception{StandardError} since it is technically not an error.
\versionadded{2.5} \versionadded{2.5}
\versionchanged[Changed to inherit from Exception instead of
StandardError]{3.0}
\end{excdesc} \end{excdesc}
\begin{excdesc}{IOError} \begin{excdesc}{IOError}
@ -257,10 +250,9 @@ Raised when an \keyword{assert} statement fails.
\begin{excdesc}{StopIteration} \begin{excdesc}{StopIteration}
Raised by builtin \function{next()} and an iterator's \method{__next__()} Raised by builtin \function{next()} and an iterator's \method{__next__()}
method to signal that there are no further values. method to signal that there are no further values.
This is derived from \exception{Exception} rather than
\exception{StandardError}, since this is not considered an error in
its normal application.
\versionadded{2.2} \versionadded{2.2}
\versionchanged[Changed to inherit from Exception instead of
StandardError]{3.0}
\end{excdesc} \end{excdesc}
@ -304,7 +296,7 @@ Raised when an \keyword{assert} statement fails.
Instances have an attribute \member{code} which is set to the Instances have an attribute \member{code} which is set to the
proposed exit status or error message (defaulting to \code{None}). proposed exit status or error message (defaulting to \code{None}).
Also, this exception derives directly from \exception{BaseException} and Also, this exception derives directly from \exception{BaseException} and
not \exception{StandardError}, since it is not technically an error. not \exception{Exception}, since it is not technically an error.
A call to \function{sys.exit()} is translated into an exception so that A call to \function{sys.exit()} is translated into an exception so that
clean-up handlers (\keyword{finally} clauses of \keyword{try} statements) clean-up handlers (\keyword{finally} clauses of \keyword{try} statements)
@ -315,7 +307,7 @@ Raised when an \keyword{assert} statement fails.
\function{fork()}). \function{fork()}).
The exception inherits from \exception{BaseException} instead of The exception inherits from \exception{BaseException} instead of
\exception{StandardError} or \exception{Exception} so that it is not \exception{Exception} so that it is not
accidentally caught by code that catches \exception{Exception}. This allows accidentally caught by code that catches \exception{Exception}. This allows
the exception to properly propagate up and cause the interpreter to exit. the exception to properly propagate up and cause the interpreter to exit.
\versionchanged[Changed to inherit from \exception{BaseException}]{2.5} \versionchanged[Changed to inherit from \exception{BaseException}]{2.5}

View File

@ -46,6 +46,7 @@ made. When \var{user} is given, additionally the method call
The optional \var{timeout} parameter specifies a timeout in seconds for the The optional \var{timeout} parameter specifies a timeout in seconds for the
connection attempt (if is not specified, or passed as None, the global connection attempt (if is not specified, or passed as None, the global
default timeout setting will be used). default timeout setting will be used).
\versionchanged[\var{timeout} was added]{2.6}
\end{classdesc} \end{classdesc}
\begin{datadesc}{all_errors} \begin{datadesc}{all_errors}
@ -117,6 +118,8 @@ the connection attempt. If is not specified, or passed as None, the
object timeout is used (the timeout that you passed when instantiating the object timeout is used (the timeout that you passed when instantiating the
class); if the object timeout is also None, the global default timeout class); if the object timeout is also None, the global default timeout
setting will be used. setting will be used.
\versionchanged[\var{timeout} was added]{2.6}
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[FTP]{getwelcome}{} \begin{methoddesc}[FTP]{getwelcome}{}

View File

@ -104,6 +104,14 @@ def my_import(name):
\versionadded{2.3} \versionadded{2.3}
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{bin}{x}
Convert an integer number to a binary string.
The result is a valid Python expression. If \var{x} is not a Python
\class{int} object, it has to define an \method{__index__} method
that returns an integer.
\versionadded{3.0}
\end{funcdesc}
\begin{funcdesc}{bool}{\optional{x}} \begin{funcdesc}{bool}{\optional{x}}
Convert a value to a Boolean, using the standard truth testing Convert a value to a Boolean, using the standard truth testing
procedure. If \var{x} is false or omitted, this returns procedure. If \var{x} is false or omitted, this returns
@ -540,8 +548,10 @@ class C:
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{hex}{x} \begin{funcdesc}{hex}{x}
Convert an integer number (of any size) to a hexadecimal string. Convert an integer number to a hexadecimal string.
The result is a valid Python expression. The result is a valid Python expression. If \var{x} is not a Python
\class{int} object, it has to define an \method{__index__} method
that returns an integer.
\versionchanged[Formerly only returned an unsigned literal]{2.4} \versionchanged[Formerly only returned an unsigned literal]{2.4}
\end{funcdesc} \end{funcdesc}
@ -559,8 +569,7 @@ class C:
representable as a Python integer, possibly embedded in whitespace. representable as a Python integer, possibly embedded in whitespace.
The \var{radix} parameter gives the base for the The \var{radix} parameter gives the base for the
conversion and may be any integer in the range [2, 36], or zero. If conversion and may be any integer in the range [2, 36], or zero. If
\var{radix} is zero, the proper radix is guessed based on the \var{radix} is zero, the interpretation is the same as for integer
contents of string; the interpretation is the same as for integer
literals. If \var{radix} is specified and \var{x} is not a string, literals. If \var{radix} is specified and \var{x} is not a string,
\exception{TypeError} is raised. \exception{TypeError} is raised.
Otherwise, the argument may be a plain or Otherwise, the argument may be a plain or
@ -707,8 +716,10 @@ class C:
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{oct}{x} \begin{funcdesc}{oct}{x}
Convert an integer number (of any size) to an octal string. The Convert an integer number to an octal string. The
result is a valid Python expression. result is a valid Python expression. If \var{x} is not a Python
\class{int} object, it has to define an \method{__index__} method
that returns an integer.
\versionchanged[Formerly only returned an unsigned literal]{2.4} \versionchanged[Formerly only returned an unsigned literal]{2.4}
\end{funcdesc} \end{funcdesc}

View File

@ -49,6 +49,7 @@ the server at the same host and port:
>>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10) >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10)
\end{verbatim} \end{verbatim}
\versionadded{2.0} \versionadded{2.0}
\versionchanged[\var{timeout} was added]{2.6}
\end{classdesc} \end{classdesc}
\begin{classdesc}{HTTPSConnection}{host\optional{, port\optional{, \begin{classdesc}{HTTPSConnection}{host\optional{, port\optional{,
@ -63,6 +64,7 @@ key. \var{cert_file} is a PEM formatted certificate chain file.
\warning{This does not do any certificate verification!} \warning{This does not do any certificate verification!}
\versionadded{2.0} \versionadded{2.0}
\versionchanged[\var{timeout} was added]{2.6}
\end{classdesc} \end{classdesc}
\begin{classdesc}{HTTPResponse}{sock\optional{, debuglevel=0}\optional{, strict=0}} \begin{classdesc}{HTTPResponse}{sock\optional{, debuglevel=0}\optional{, strict=0}}

View File

@ -35,6 +35,8 @@ If \var{port} is omitted, the standard POP3 port (110) is used.
The optional \var{timeout} parameter specifies a timeout in seconds for the The optional \var{timeout} parameter specifies a timeout in seconds for the
connection attempt (if not specified, or passed as None, the global default connection attempt (if not specified, or passed as None, the global default
timeout setting will be used). timeout setting will be used).
\versionchanged[\var{timeout} was added]{2.6}
\end{classdesc} \end{classdesc}
\begin{classdesc}{POP3_SSL}{host\optional{, port\optional{, keyfile\optional{, certfile}}}} \begin{classdesc}{POP3_SSL}{host\optional{, port\optional{, keyfile\optional{, certfile}}}}

View File

@ -29,6 +29,8 @@ default timeout setting will be used).
For normal use, you should only require the initialization/connect, For normal use, you should only require the initialization/connect,
\method{sendmail()}, and \method{quit()} methods. An example is \method{sendmail()}, and \method{quit()} methods. An example is
included below. included below.
\versionchanged[\var{timeout} was added]{2.6}
\end{classdesc} \end{classdesc}
\begin{classdesc}{SMTP_SSL}{\optional{host\optional{, port\optional{, \begin{classdesc}{SMTP_SSL}{\optional{host\optional{, port\optional{,
@ -45,6 +47,8 @@ certificate chain file for the SSL connection.
The optional \var{timeout} parameter specifies a timeout in seconds for the The optional \var{timeout} parameter specifies a timeout in seconds for the
connection attempt (if not specified, or passed as None, the global connection attempt (if not specified, or passed as None, the global
default timeout setting will be used). default timeout setting will be used).
\versionchanged[\var{timeout} was added]{2.6}
\end{classdesc} \end{classdesc}
\begin{classdesc}{LMTP}{\optional{host\optional{, port\optional{, \begin{classdesc}{LMTP}{\optional{host\optional{, port\optional{,

View File

@ -177,6 +177,7 @@ higher-level protocols, it is not normally used directly from
application-level code. Passing the optional \var{timeout} parameter application-level code. Passing the optional \var{timeout} parameter
will set the timeout on the socket instance (if it is not given or will set the timeout on the socket instance (if it is not given or
\code{None}, the global default timeout setting is used). \code{None}, the global default timeout setting is used).
\versionadded{2.6}
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getaddrinfo}{host, port\optional{, family\optional{, \begin{funcdesc}{getaddrinfo}{host, port\optional{, family\optional{,

View File

@ -40,6 +40,7 @@ This class has many \method{read_*()} methods. Note that some of them
raise \exception{EOFError} when the end of the connection is read, raise \exception{EOFError} when the end of the connection is read,
because they can return an empty string for other reasons. See the because they can return an empty string for other reasons. See the
individual descriptions below. individual descriptions below.
\versionchanged[\var{timeout} was added]{2.6}
\end{classdesc} \end{classdesc}
@ -123,6 +124,7 @@ connection attempt (if not specified, or passed as None, the global default
timeout setting will be used). timeout setting will be used).
Do not try to reopen an already connected instance. Do not try to reopen an already connected instance.
\versionchanged[\var{timeout} was added]{2.6}
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[Telnet]{msg}{msg\optional{, *args}} \begin{methoddesc}[Telnet]{msg}{msg\optional{, *args}}

View File

@ -174,11 +174,14 @@ until a call to \method{release()} in another thread changes it to
unlocked, then the \method{acquire()} call resets it to locked and unlocked, then the \method{acquire()} call resets it to locked and
returns. The \method{release()} method should only be called in the returns. The \method{release()} method should only be called in the
locked state; it changes the state to unlocked and returns locked state; it changes the state to unlocked and returns
immediately. When more than one thread is blocked in immediately. If an attempt is made to release an unlocked lock, a
\method{acquire()} waiting for the state to turn to unlocked, only one \exception{RuntimeError} will be raised.
thread proceeds when a \method{release()} call resets the state to
unlocked; which one of the waiting threads proceeds is not defined, When more than one thread is blocked in \method{acquire()} waiting for
and may vary across implementations. the state to turn to unlocked, only one thread proceeds when a
\method{release()} call resets the state to unlocked; which one of the
waiting threads proceeds is not defined, and may vary across
implementations.
All methods are executed atomically. All methods are executed atomically.
@ -257,8 +260,9 @@ become unlocked, allow exactly one of them to proceed. If after the
decrement the recursion level is still nonzero, the lock remains decrement the recursion level is still nonzero, the lock remains
locked and owned by the calling thread. locked and owned by the calling thread.
Only call this method when the calling thread owns the lock. Only call this method when the calling thread owns the lock. A
Do not call this method when the lock is unlocked. \exception{RuntimeError} is raised if this method is called when the
lock is unlocked.
There is no return value. There is no return value.
\end{methoddesc} \end{methoddesc}
@ -275,7 +279,8 @@ A condition variable has \method{acquire()} and \method{release()}
methods that call the corresponding methods of the associated lock. methods that call the corresponding methods of the associated lock.
It also has a \method{wait()} method, and \method{notify()} and It also has a \method{wait()} method, and \method{notify()} and
\method{notifyAll()} methods. These three must only be called when \method{notifyAll()} methods. These three must only be called when
the calling thread has acquired the lock. the calling thread has acquired the lock, otherwise a
\exception{RuntimeError} is raised.
The \method{wait()} method releases the lock, and then blocks until it The \method{wait()} method releases the lock, and then blocks until it
is awakened by a \method{notify()} or \method{notifyAll()} call for is awakened by a \method{notify()} or \method{notifyAll()} call for
@ -343,9 +348,9 @@ lock; there is no return value.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{wait}{\optional{timeout}} \begin{methoddesc}{wait}{\optional{timeout}}
Wait until notified or until a timeout occurs. Wait until notified or until a timeout occurs. If the calling thread
This must only be called when the calling thread has acquired the has not acquired the lock when this method is called, a
lock. \exception{RuntimeError} is raised.
This method releases the underlying lock, and then blocks until it is This method releases the underlying lock, and then blocks until it is
awakened by a \method{notify()} or \method{notifyAll()} call for the awakened by a \method{notify()} or \method{notifyAll()} call for the
@ -367,9 +372,10 @@ when the lock is reacquired.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{notify}{} \begin{methoddesc}{notify}{}
Wake up a thread waiting on this condition, if any. Wake up a thread waiting on this condition, if any. Wait until
This must only be called when the calling thread has acquired the notified or until a timeout occurs. If the calling thread has not
lock. acquired the lock when this method is called, a
\exception{RuntimeError} is raised.
This method wakes up one of the threads waiting for the condition This method wakes up one of the threads waiting for the condition
variable, if any are waiting; it is a no-op if no threads are waiting. variable, if any are waiting; it is a no-op if no threads are waiting.
@ -386,7 +392,9 @@ Note: the awakened thread does not actually return from its
\begin{methoddesc}{notifyAll}{} \begin{methoddesc}{notifyAll}{}
Wake up all threads waiting on this condition. This method acts like Wake up all threads waiting on this condition. This method acts like
\method{notify()}, but wakes up all waiting threads instead of one. \method{notify()}, but wakes up all waiting threads instead of one. If
the calling thread has not acquired the lock when this method is
called, a \exception{RuntimeError} is raised.
\end{methoddesc} \end{methoddesc}
@ -404,8 +412,9 @@ finds that it is zero, it blocks, waiting until some other thread
calls \method{release()}. calls \method{release()}.
\begin{classdesc}{Semaphore}{\optional{value}} \begin{classdesc}{Semaphore}{\optional{value}}
The optional argument gives the initial value for the internal The optional argument gives the initial \var{value} for the internal
counter; it defaults to \code{1}. counter; it defaults to \code{1}. If the \var{value} given is less
than 0, \exception{ValueError} is raised.
\end{classdesc} \end{classdesc}
\begin{methoddesc}{acquire}{\optional{blocking}} \begin{methoddesc}{acquire}{\optional{blocking}}
@ -586,9 +595,12 @@ before doing anything else to the thread.
\begin{methoddesc}{start}{} \begin{methoddesc}{start}{}
Start the thread's activity. Start the thread's activity.
This must be called at most once per thread object. It It must be called at most once per thread object. It arranges for the
arranges for the object's \method{run()} method to be invoked in a object's \method{run()} method to be invoked in a separate thread of
separate thread of control. control.
This method will raise a \exception{RuntimeException} if called more
than once on the same thread object.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{run}{} \begin{methoddesc}{run}{}
@ -618,11 +630,10 @@ operation will block until the thread terminates.
A thread can be \method{join()}ed many times. A thread can be \method{join()}ed many times.
A thread cannot join itself because this would cause a \method{join()} may throw a \exception{RuntimeError}, if an attempt is
deadlock. made to join the current thread as that would cause a deadlock. It is
also an error to \method{join()} a thread before it has been started
It is an error to attempt to \method{join()} a thread before it has and attempts to do so raises same exception.
been started.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{getName}{} \begin{methoddesc}{getName}{}
@ -651,7 +662,8 @@ Return the thread's daemon flag.
\begin{methoddesc}{setDaemon}{daemonic} \begin{methoddesc}{setDaemon}{daemonic}
Set the thread's daemon flag to the Boolean value \var{daemonic}. Set the thread's daemon flag to the Boolean value \var{daemonic}.
This must be called before \method{start()} is called. This must be called before \method{start()} is called, otherwise
\exception{RuntimeError} is raised.
The initial value is inherited from the creating thread. The initial value is inherited from the creating thread.

View File

@ -14,7 +14,7 @@ authentication, redirections, cookies and more.
The \module{urllib2} module defines the following functions: The \module{urllib2} module defines the following functions:
\begin{funcdesc}{urlopen}{url\optional{, data}} \begin{funcdesc}{urlopen}{url\optional{, data}\optional{, timeout}}
Open the URL \var{url}, which can be either a string or a \class{Request} Open the URL \var{url}, which can be either a string or a \class{Request}
object. object.
@ -27,6 +27,11 @@ parameter is provided. \var{data} should be a buffer in the standard
\function{urllib.urlencode()} function takes a mapping or sequence of \function{urllib.urlencode()} function takes a mapping or sequence of
2-tuples and returns a string in this format. 2-tuples and returns a string in this format.
The optional \var{timeout} parameter specifies a timeout in seconds for the
connection attempt (if not specified, or passed as None, the global default
timeout setting will be used). This actually only work for HTTP, HTTPS, FTP
and FTPS connections.
This function returns a file-like object with two additional methods: This function returns a file-like object with two additional methods:
\begin{itemize} \begin{itemize}
@ -40,6 +45,8 @@ Raises \exception{URLError} on errors.
Note that \code{None} may be returned if no handler handles the Note that \code{None} may be returned if no handler handles the
request (though the default installed global \class{OpenerDirector} request (though the default installed global \class{OpenerDirector}
uses \class{UnknownHandler} to ensure this never happens). uses \class{UnknownHandler} to ensure this never happens).
\versionchanged[\var{timeout} was added]{2.6}
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{install_opener}{opener} \begin{funcdesc}{install_opener}{opener}
@ -351,12 +358,18 @@ that HTTP errors are a special case).
\end{itemize} \end{itemize}
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[OpenerDirector]{open}{url\optional{, data}} \begin{methoddesc}[OpenerDirector]{open}{url\optional{, data}{\optional{, timeout}}}
Open the given \var{url} (which can be a request object or a string), Open the given \var{url} (which can be a request object or a string),
optionally passing the given \var{data}. optionally passing the given \var{data}.
Arguments, return values and exceptions raised are the same as those Arguments, return values and exceptions raised are the same as those
of \function{urlopen()} (which simply calls the \method{open()} method of \function{urlopen()} (which simply calls the \method{open()} method
on the currently installed global \class{OpenerDirector}). on the currently installed global \class{OpenerDirector}). The optional
\var{timeout} parameter specifies a timeout in seconds for the connection
attempt (if not specified, or passed as None, the global default timeout
setting will be used; this actually only work for HTTP, HTTPS, FTP
and FTPS connections).
\versionchanged[\var{timeout} was added]{2.6}
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[OpenerDirector]{error}{proto\optional{, \begin{methoddesc}[OpenerDirector]{error}{proto\optional{,

View File

@ -565,6 +565,7 @@ number and an imaginary number).
\index{floating point literal} \index{floating point literal}
\index{hexadecimal literal} \index{hexadecimal literal}
\index{octal literal} \index{octal literal}
\index{binary literal}
\index{decimal literal} \index{decimal literal}
\index{imaginary literal} \index{imaginary literal}
\index{complex!literal} \index{complex!literal}
@ -574,35 +575,32 @@ Note that numeric literals do not include a sign; a phrase like
`\code{-}' and the literal \code{1}. `\code{-}' and the literal \code{1}.
\subsection{Integer and long integer literals\label{integers}} \subsection{Integer literals\label{integers}}
Integer and long integer literals are described by the following Integer literals are described by the following
lexical definitions: lexical definitions:
\begin{productionlist} \begin{productionlist}
\production{longinteger}
{\token{integer} ("l" | "L")}
\production{integer} \production{integer}
{\token{decimalinteger} | \token{octinteger} | \token{hexinteger}} {\token{decimalinteger} | \token{octinteger} | \token{hexinteger}}
\production{decimalinteger} \production{decimalinteger}
{\token{nonzerodigit} \token{digit}* | "0"} {\token{nonzerodigit} \token{digit}* | "0"+}
\production{octinteger} \production{octinteger}
{"0" \token{octdigit}+} {"0" ("o" | "O") \token{octdigit}+}
\production{hexinteger} \production{hexinteger}
{"0" ("x" | "X") \token{hexdigit}+} {"0" ("x" | "X") \token{hexdigit}+}
\production{bininteger}
{"0" ("b" | "B") \token{bindigit}+}
\production{nonzerodigit} \production{nonzerodigit}
{"1"..."9"} {"1"..."9"}
\production{octdigit} \production{octdigit}
{"0"..."7"} {"0"..."7"}
\production{hexdigit} \production{hexdigit}
{\token{digit} | "a"..."f" | "A"..."F"} {\token{digit} | "a"..."f" | "A"..."F"}
\production{bindigit}
{"0"..."1"}
\end{productionlist} \end{productionlist}
Although both lower case \character{l} and upper case \character{L} are
allowed as suffix for long integers, it is strongly recommended to always
use \character{L}, since the letter \character{l} looks too much like the
digit \character{1}.
Plain integer literals that are above the largest representable plain Plain integer literals that are above the largest representable plain
integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted
as if they were long integers instead.\footnote{In versions of Python as if they were long integers instead.\footnote{In versions of Python
@ -613,13 +611,16 @@ taken as the negative plain integer obtained by subtracting 4294967296
from their unsigned value.} There is no limit for long integer from their unsigned value.} There is no limit for long integer
literals apart from what can be stored in available memory. literals apart from what can be stored in available memory.
Some examples of plain integer literals (first row) and long integer Note that leading zeros in a non-zero decimal number are not allowed.
literals (second and third rows): This is for disambiguation with C-style octal literals, which Python
used before version 3.0.
Some examples of integer literals:
\begin{verbatim} \begin{verbatim}
7 2147483647 0177 7 2147483647 0o177 0b100110111
3L 79228162514264337593543950336L 0377L 0x100000000L 3 79228162514264337593543950336 0o377 0x100000000
79228162514264337593543950336 0xdeadbeef 79228162514264337593543950336 0xdeadbeef
\end{verbatim} \end{verbatim}
@ -644,12 +645,10 @@ definitions:
{("e" | "E") ["+" | "-"] \token{digit}+} {("e" | "E") ["+" | "-"] \token{digit}+}
\end{productionlist} \end{productionlist}
Note that the integer and exponent parts of floating point numbers Note that the integer and exponent parts are always interpreted using
can look like octal integers, but are interpreted using radix 10. For radix 10. For example, \samp{077e010} is legal, and denotes the same
example, \samp{077e010} is legal, and denotes the same number number as \samp{77e10}.
as \samp{77e10}. The allowed range of floating point literals is implementation-dependent.
The allowed range of floating point literals is
implementation-dependent.
Some examples of floating point literals: Some examples of floating point literals:
\begin{verbatim} \begin{verbatim}

View File

@ -2033,17 +2033,11 @@ and \function{float()}\bifuncindex{float}. Should return a value of
the appropriate type. the appropriate type.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[numeric object]{__oct__}{self}
\methodline[numeric object]{__hex__}{self}
Called to implement the built-in functions
\function{oct()}\bifuncindex{oct} and
\function{hex()}\bifuncindex{hex}. Should return a string value.
\end{methoddesc}
\begin{methoddesc}[numeric object]{__index__}{self} \begin{methoddesc}[numeric object]{__index__}{self}
Called to implement \function{operator.index()}. Also called whenever Called to implement \function{operator.index()}. Also called whenever
Python needs an integer object (such as in slicing). Must return an Python needs an integer object (such as in slicing, or in the built-in
integer (int or long). \function{bin()}, \function{hex()} and \function{oct()} functions).
Must return an integer (int or long).
\versionadded{2.5} \versionadded{2.5}
\end{methoddesc} \end{methoddesc}

View File

@ -2689,7 +2689,7 @@ standard module \module{__builtin__}\refbimodindex{__builtin__}:
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError', 'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'RuntimeWarning', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
@ -2734,9 +2734,9 @@ possible structure for your package (expressed in terms of a
hierarchical filesystem): hierarchical filesystem):
\begin{verbatim} \begin{verbatim}
Sound/ Top-level package sound/ Top-level package
__init__.py Initialize the sound package __init__.py Initialize the sound package
Formats/ Subpackage for file format conversions formats/ Subpackage for file format conversions
__init__.py __init__.py
wavread.py wavread.py
wavwrite.py wavwrite.py
@ -2745,13 +2745,13 @@ Sound/ Top-level package
auread.py auread.py
auwrite.py auwrite.py
... ...
Effects/ Subpackage for sound effects effects/ Subpackage for sound effects
__init__.py __init__.py
echo.py echo.py
surround.py surround.py
reverse.py reverse.py
... ...
Filters/ Subpackage for filters filters/ Subpackage for filters
__init__.py __init__.py
equalizer.py equalizer.py
vocoder.py vocoder.py
@ -2774,20 +2774,20 @@ Users of the package can import individual modules from the
package, for example: package, for example:
\begin{verbatim} \begin{verbatim}
import Sound.Effects.echo import sound.effects.echo
\end{verbatim} \end{verbatim}
This loads the submodule \module{Sound.Effects.echo}. It must be referenced This loads the submodule \module{sound.effects.echo}. It must be referenced
with its full name. with its full name.
\begin{verbatim} \begin{verbatim}
Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4) sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
\end{verbatim} \end{verbatim}
An alternative way of importing the submodule is: An alternative way of importing the submodule is:
\begin{verbatim} \begin{verbatim}
from Sound.Effects import echo from sound.effects import echo
\end{verbatim} \end{verbatim}
This also loads the submodule \module{echo}, and makes it available without This also loads the submodule \module{echo}, and makes it available without
@ -2800,7 +2800,7 @@ echo.echofilter(input, output, delay=0.7, atten=4)
Yet another variation is to import the desired function or variable directly: Yet another variation is to import the desired function or variable directly:
\begin{verbatim} \begin{verbatim}
from Sound.Effects.echo import echofilter from sound.effects.echo import echofilter
\end{verbatim} \end{verbatim}
Again, this loads the submodule \module{echo}, but this makes its function Again, this loads the submodule \module{echo}, but this makes its function
@ -2827,7 +2827,7 @@ class or function or variable defined in the previous item.
%The \code{__all__} Attribute %The \code{__all__} Attribute
\ttindex{__all__} \ttindex{__all__}
Now what happens when the user writes \code{from Sound.Effects import Now what happens when the user writes \code{from sound.effects import
*}? Ideally, one would hope that this somehow goes out to the *}? Ideally, one would hope that this somehow goes out to the
filesystem, finds which submodules are present in the package, and filesystem, finds which submodules are present in the package, and
imports them all. Unfortunately, this operation does not work very imports them all. Unfortunately, this operation does not work very
@ -2849,19 +2849,19 @@ encountered. It is up to the package author to keep this list
up-to-date when a new version of the package is released. Package up-to-date when a new version of the package is released. Package
authors may also decide not to support it, if they don't see a use for authors may also decide not to support it, if they don't see a use for
importing * from their package. For example, the file importing * from their package. For example, the file
\file{Sounds/Effects/__init__.py} could contain the following code: \file{sounds/effects/__init__.py} could contain the following code:
\begin{verbatim} \begin{verbatim}
__all__ = ["echo", "surround", "reverse"] __all__ = ["echo", "surround", "reverse"]
\end{verbatim} \end{verbatim}
This would mean that \code{from Sound.Effects import *} would This would mean that \code{from sound.effects import *} would
import the three named submodules of the \module{Sound} package. import the three named submodules of the \module{sound} package.
If \code{__all__} is not defined, the statement \code{from Sound.Effects If \code{__all__} is not defined, the statement \code{from sound.effects
import *} does \emph{not} import all submodules from the package import *} does \emph{not} import all submodules from the package
\module{Sound.Effects} into the current namespace; it only ensures that the \module{sound.effects} into the current namespace; it only ensures that the
package \module{Sound.Effects} has been imported (possibly running any package \module{sound.effects} has been imported (possibly running any
initialization code in \file{__init__.py}) and then imports whatever names are initialization code in \file{__init__.py}) and then imports whatever names are
defined in the package. This includes any names defined (and defined in the package. This includes any names defined (and
submodules explicitly loaded) by \file{__init__.py}. It also includes any submodules explicitly loaded) by \file{__init__.py}. It also includes any
@ -2869,14 +2869,14 @@ submodules of the package that were explicitly loaded by previous
import statements. Consider this code: import statements. Consider this code:
\begin{verbatim} \begin{verbatim}
import Sound.Effects.echo import sound.effects.echo
import Sound.Effects.surround import sound.effects.surround
from Sound.Effects import * from sound.effects import *
\end{verbatim} \end{verbatim}
In this example, the echo and surround modules are imported in the In this example, the echo and surround modules are imported in the
current namespace because they are defined in the current namespace because they are defined in the
\module{Sound.Effects} package when the \code{from...import} statement \module{sound.effects} package when the \code{from...import} statement
is executed. (This also works when \code{__all__} is defined.) is executed. (This also works when \code{__all__} is defined.)
Note that in general the practice of importing \code{*} from a module or Note that in general the practice of importing \code{*} from a module or
@ -2904,12 +2904,12 @@ which the current module is a submodule), the \keyword{import}
statement looks for a top-level module with the given name. statement looks for a top-level module with the given name.
When packages are structured into subpackages (as with the When packages are structured into subpackages (as with the
\module{Sound} package in the example), there's no shortcut to refer \module{sound} package in the example), there's no shortcut to refer
to submodules of sibling packages - the full name of the subpackage to submodules of sibling packages - the full name of the subpackage
must be used. For example, if the module must be used. For example, if the module
\module{Sound.Filters.vocoder} needs to use the \module{echo} module \module{sound.filters.vocoder} needs to use the \module{echo} module
in the \module{Sound.Effects} package, it can use \code{from in the \module{sound.effects} package, it can use \code{from
Sound.Effects import echo}. sound.effects import echo}.
Starting with Python 2.5, in addition to the implicit relative imports Starting with Python 2.5, in addition to the implicit relative imports
described above, you can write explicit relative imports with the described above, you can write explicit relative imports with the
@ -2920,8 +2920,8 @@ module for example, you might use:
\begin{verbatim} \begin{verbatim}
from . import echo from . import echo
from .. import Formats from .. import formats
from ..Filters import equalizer from ..filters import equalizer
\end{verbatim} \end{verbatim}
Note that both explicit and implicit relative imports are based on the Note that both explicit and implicit relative imports are based on the

View File

@ -53,7 +53,7 @@
\tableofcontents \tableofcontents
This article explains the new features in Python 2.6. No release date This article explains the new features in Python 2.6. No release date
for Python 2.6 has been set; it will probably be released in late 2007. for Python 2.6 has been set; it will probably be released in mid 2008.
% Compare with previous release in 2 - 3 sentences here. % Compare with previous release in 2 - 3 sentences here.

View File

@ -851,6 +851,14 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
expression: o1 |= o2. expression: o1 |= o2.
*/ */
PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base);
/*
Returns the integer n converted to a string with a base, with a base
marker of 0b, 0o or 0x prefixed if applicable.
If n is not an int object, it is converted with PyNumber_Index first.
*/
/* Sequence protocol:*/ /* Sequence protocol:*/

View File

@ -109,6 +109,11 @@ PyAPI_FUNC(int) _PyLong_AsByteArray(PyLongObject* v,
unsigned char* bytes, size_t n, unsigned char* bytes, size_t n,
int little_endian, int is_signed); int little_endian, int is_signed);
/* _PyLong_Format: Convert the long to a string object with given base,
appending a base prefix of 0[box] if base is 2, 8 or 16. */
PyAPI_FUNC(PyObject *) _PyLong_Format(PyObject *aa, int base);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -171,6 +171,7 @@ typedef struct {
unaryfunc nb_int; unaryfunc nb_int;
unaryfunc nb_long; unaryfunc nb_long;
unaryfunc nb_float; unaryfunc nb_float;
/* NB: nb_oct and nb_hex are not used anymore. */
unaryfunc nb_oct; unaryfunc nb_oct;
unaryfunc nb_hex; unaryfunc nb_hex;

View File

@ -105,7 +105,6 @@ PyAPI_DATA(PyObject *) PyExc_BaseException;
PyAPI_DATA(PyObject *) PyExc_Exception; PyAPI_DATA(PyObject *) PyExc_Exception;
PyAPI_DATA(PyObject *) PyExc_StopIteration; PyAPI_DATA(PyObject *) PyExc_StopIteration;
PyAPI_DATA(PyObject *) PyExc_GeneratorExit; PyAPI_DATA(PyObject *) PyExc_GeneratorExit;
PyAPI_DATA(PyObject *) PyExc_StandardError;
PyAPI_DATA(PyObject *) PyExc_ArithmeticError; PyAPI_DATA(PyObject *) PyExc_ArithmeticError;
PyAPI_DATA(PyObject *) PyExc_LookupError; PyAPI_DATA(PyObject *) PyExc_LookupError;

View File

@ -50,6 +50,22 @@ Used in: PY_LONG_LONG
#ifdef HAVE_LONG_LONG #ifdef HAVE_LONG_LONG
#ifndef PY_LONG_LONG #ifndef PY_LONG_LONG
#define PY_LONG_LONG long long #define PY_LONG_LONG long long
#if defined(LLONG_MAX)
/* If LLONG_MAX is defined in limits.h, use that. */
#define PY_LLONG_MIN LLONG_MIN
#define PY_LLONG_MAX LLONG_MAX
#define PY_ULLONG_MAX ULLONG_MAX
#elif defined(__LONG_LONG_MAX__)
/* Otherwise, if GCC has a builtin define, use that. */
#define PY_LLONG_MAX __LONG_LONG_MAX__
#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
#define PY_ULLONG_MAX (__LONG_LONG_MAX__*2ULL + 1ULL)
#else
/* Otherwise, rely on two's complement. */
#define PY_ULLONG_MAX (~0ULL)
#define PY_LLONG_MAX ((long long)(PY_ULLONG_MAX>>1))
#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
#endif /* LLONG_MAX */
#endif #endif
#endif /* HAVE_LONG_LONG */ #endif /* HAVE_LONG_LONG */

View File

@ -353,7 +353,7 @@ def executable(path):
st = os.stat(path) st = os.stat(path)
except os.error: except os.error:
return False return False
return st.st_mode & 0111 != 0 return st.st_mode & 0o111 != 0
def test(HandlerClass = CGIHTTPRequestHandler, def test(HandlerClass = CGIHTTPRequestHandler,

535
Lib/_abcoll.py Normal file
View File

@ -0,0 +1,535 @@
# Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate ceratin
bootstrapping issues. Unit tests are in test_collections.
"""
from abc import ABCMeta, abstractmethod
__all__ = ["Hashable", "Iterable", "Iterator",
"Sized", "Container", "Callable",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
]
### ONE-TRICK PONIES ###
class Hashable(metaclass=ABCMeta):
@abstractmethod
def __hash__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Hashable:
for B in C.__mro__:
if "__hash__" in B.__dict__:
if B.__dict__["__hash__"]:
return True
break
return NotImplemented
class Iterable(metaclass=ABCMeta):
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
if any("__iter__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
Iterable.register(bytes)
class Iterator(metaclass=ABCMeta):
@abstractmethod
def __next__(self):
raise StopIteration
def __iter__(self):
return self
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
if any("__next__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Sized(metaclass=ABCMeta):
@abstractmethod
def __len__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
if any("__len__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Container(metaclass=ABCMeta):
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if any("__contains__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Callable(metaclass=ABCMeta):
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Callable:
if any("__call__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
### SETS ###
class Set(metaclass=ABCMeta):
"""A set is a finite, iterable container.
This class provides concrete generic implementations of all
methods except for __contains__, __iter__ and __len__.
To override the comparisons (presumably for speed, as the
semantics are fixed), all you have to do is redefine __le__ and
then the other operations will automatically follow suit.
"""
@abstractmethod
def __contains__(self, value):
return False
@abstractmethod
def __iter__(self):
while False:
yield None
@abstractmethod
def __len__(self):
return 0
def __le__(self, other):
if not isinstance(other, Set):
return NotImplemented
if len(self) > len(other):
return False
for elem in self:
if elem not in other:
return False
return True
def __lt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) < len(other) and self.__le__(other)
def __eq__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) == len(other) and self.__le__(other)
@classmethod
def _from_iterable(cls, it):
return frozenset(it)
def __and__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
return self._from_iterable(value for value in other if value in self)
def __or__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
return self._from_iterable(itertools.chain(self, other))
def __sub__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return self._from_iterable(value for value in self
if value not in other)
def __xor__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return (self - other) | (other - self)
def _hash(self):
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
regardless of the order of the elements; so there's not much
freedom for __eq__ or __hash__. We match the algorithm used
by the built-in frozenset type.
"""
MAX = sys.maxint
MASK = 2 * MAX + 1
n = len(self)
h = 1927868237 * (n + 1)
h &= MASK
for x in self:
hx = hash(x)
h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
h &= MASK
h = h * 69069 + 907133923
h &= MASK
if h > MAX:
h -= MASK + 1
if h == -1:
h = 590923713
return h
Set.register(frozenset)
class MutableSet(Set):
@abstractmethod
def add(self, value):
"""Return True if it was added, False if already there."""
raise NotImplementedError
@abstractmethod
def discard(self, value):
"""Return True if it was deleted, False if not there."""
raise NotImplementedError
def pop(self):
"""Return the popped value. Raise KeyError if empty."""
it = iter(self)
try:
value = it.__next__()
except StopIteration:
raise KeyError
self.discard(value)
return value
def toggle(self, value):
"""Return True if it was added, False if deleted."""
# XXX This implementation is not thread-safe
if value in self:
self.discard(value)
return False
else:
self.add(value)
return True
def clear(self):
"""This is slow (creates N new iterators!) but effective."""
try:
while True:
self.pop()
except KeyError:
pass
def __ior__(self, it: Iterable):
for value in it:
self.add(value)
return self
def __iand__(self, c: Container):
for value in self:
if value not in c:
self.discard(value)
return self
def __ixor__(self, it: Iterable):
# This calls toggle(), so if that is overridded, we call the override
for value in it:
self.toggle(it)
return self
def __isub__(self, it: Iterable):
for value in it:
self.discard(value)
return self
MutableSet.register(set)
### MAPPINGS ###
class Mapping(metaclass=ABCMeta):
@abstractmethod
def __getitem__(self, key):
raise KeyError
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
@abstractmethod
def __len__(self):
return 0
@abstractmethod
def __iter__(self):
while False:
yield None
def keys(self):
return KeysView(self)
def items(self):
return ItemsView(self)
def values(self):
return ValuesView(self)
class MappingView(metaclass=ABCMeta):
def __init__(self, mapping):
self._mapping = mapping
def __len__(self):
return len(self._mapping)
class KeysView(MappingView, Set):
def __contains__(self, key):
return key in self._mapping
def __iter__(self):
for key in self._mapping:
yield key
KeysView.register(type({}.keys()))
class ItemsView(MappingView, Set):
def __contains__(self, item):
key, value = item
try:
v = self._mapping[key]
except KeyError:
return False
else:
return v == value
def __iter__(self):
for key in self._mapping:
yield (key, self._mapping[key])
ItemsView.register(type({}.items()))
class ValuesView(MappingView):
def __contains__(self, value):
for key in self._mapping:
if value == self._mapping[key]:
return True
return False
def __iter__(self):
for key in self._mapping:
yield self._mapping[key]
ValuesView.register(type({}.values()))
class MutableMapping(Mapping):
@abstractmethod
def __setitem__(self, key, value):
raise KeyError
@abstractmethod
def __delitem__(self, key):
raise KeyError
__marker = object()
def pop(self, key, default=__marker):
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError
value = self[key]
del self[key]
return key, value
def clear(self):
try:
while True:
self.popitem()
except KeyError:
pass
def update(self, other=(), **kwds):
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
MutableMapping.register(dict)
### SEQUENCES ###
class Sequence(metaclass=ABCMeta):
"""All the operations on a read-only sequence.
Concrete subclasses must override __new__ or __init__,
__getitem__, and __len__.
"""
@abstractmethod
def __getitem__(self, index):
raise IndexError
@abstractmethod
def __len__(self):
return 0
def __iter__(self):
i = 0
while True:
try:
v = self[i]
except IndexError:
break
yield v
i += 1
def __contains__(self, value):
for v in self:
if v == value:
return True
return False
def __reversed__(self):
for i in reversed(range(len(self))):
yield self[i]
def index(self, value):
for i, v in enumerate(self):
if v == value:
return i
raise ValueError
def count(self, value):
return sum(1 for v in self if v == value)
Sequence.register(tuple)
Sequence.register(basestring)
Sequence.register(buffer)
class MutableSequence(Sequence):
@abstractmethod
def __setitem__(self, index, value):
raise IndexError
@abstractmethod
def __delitem__(self, index):
raise IndexError
@abstractmethod
def insert(self, index, value):
raise IndexError
def append(self, value):
self.insert(len(self), value)
def reverse(self):
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i]
def extend(self, values):
for v in values:
self.append(v)
def pop(self, index=-1):
v = self[index]
del self[index]
return v
def remove(self, value):
del self[self.index(value)]
def __iadd__(self, values):
self.extend(values)
MutableSequence.register(list)
MutableSequence.register(bytes)

View File

@ -107,7 +107,7 @@ class LocaleTime(object):
# magical; just happened to have used it everywhere else where a # magical; just happened to have used it everywhere else where a
# static date was needed. # static date was needed.
am_pm = [] am_pm = []
for hour in (01,22): for hour in (1, 22):
time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0)) time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
am_pm.append(time.strftime("%p", time_tuple).lower()) am_pm.append(time.strftime("%p", time_tuple).lower())
self.am_pm = am_pm self.am_pm = am_pm
@ -186,7 +186,7 @@ class TimeRE(dict):
self.locale_time = locale_time self.locale_time = locale_time
else: else:
self.locale_time = LocaleTime() self.locale_time = LocaleTime()
base = super(TimeRE, self) base = super()
base.__init__({ base.__init__({
# The " \d" part of the regex is to make %c from ANSI C work # The " \d" part of the regex is to make %c from ANSI C work
'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
@ -250,7 +250,7 @@ class TimeRE(dict):
regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])") regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")
format = regex_chars.sub(r"\\\1", format) format = regex_chars.sub(r"\\\1", format)
whitespace_replacement = re_compile('\s+') whitespace_replacement = re_compile('\s+')
format = whitespace_replacement.sub('\s*', format) format = whitespace_replacement.sub('\s+', format)
while '%' in format: while '%' in format:
directive_index = format.index('%')+1 directive_index = format.index('%')+1
processed_format = "%s%s%s" % (processed_format, processed_format = "%s%s%s" % (processed_format,

View File

@ -3,7 +3,7 @@
Instead of Instead of
import dbm import dbm
d = dbm.open(file, 'w', 0666) d = dbm.open(file, 'w', 0o666)
use use
@ -63,7 +63,7 @@ if not _defaultmod:
error = tuple(_errors) error = tuple(_errors)
def open(file, flag = 'r', mode = 0666): def open(file, flag = 'r', mode = 0o666):
# guess the type of an existing database # guess the type of an existing database
from whichdb import whichdb from whichdb import whichdb
result=whichdb(file) result=whichdb(file)

View File

@ -294,7 +294,7 @@ class _DBWithCursor(_iter_mixin):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
# Compatibility object factory functions # Compatibility object factory functions
def hashopen(file, flag='c', mode=0666, pgsize=None, ffactor=None, nelem=None, def hashopen(file, flag='c', mode=0o666, pgsize=None, ffactor=None, nelem=None,
cachesize=None, lorder=None, hflags=0): cachesize=None, lorder=None, hflags=0):
flags = _checkflag(flag, file) flags = _checkflag(flag, file)
@ -310,7 +310,7 @@ def hashopen(file, flag='c', mode=0666, pgsize=None, ffactor=None, nelem=None,
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def btopen(file, flag='c', mode=0666, def btopen(file, flag='c', mode=0o666,
btflags=0, cachesize=None, maxkeypage=None, minkeypage=None, btflags=0, cachesize=None, maxkeypage=None, minkeypage=None,
pgsize=None, lorder=None): pgsize=None, lorder=None):
@ -328,7 +328,7 @@ def btopen(file, flag='c', mode=0666,
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def rnopen(file, flag='c', mode=0666, def rnopen(file, flag='c', mode=0o666,
rnflags=0, cachesize=None, pgsize=None, lorder=None, rnflags=0, cachesize=None, pgsize=None, lorder=None,
rlen=None, delim=None, source=None, pad=None): rlen=None, delim=None, source=None, pad=None):

View File

@ -40,7 +40,7 @@ from . import db
#------------------------------------------------------------------------ #------------------------------------------------------------------------
def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH, def open(filename, flags=db.DB_CREATE, mode=0o660, filetype=db.DB_HASH,
dbenv=None, dbname=None): dbenv=None, dbname=None):
""" """
A simple factory function for compatibility with the standard A simple factory function for compatibility with the standard

View File

@ -38,7 +38,7 @@ except NameError:
class DBIncompleteError(Exception): class DBIncompleteError(Exception):
pass pass
class TableDBError(StandardError): class TableDBError(Exception):
pass pass
class TableAlreadyExists(TableDBError): class TableAlreadyExists(TableDBError):
pass pass
@ -134,9 +134,9 @@ def contains_metastrings(s) :
class bsdTableDB : class bsdTableDB :
def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600, def __init__(self, filename, dbhome, create=0, truncate=0, mode=0o600,
recover=0, dbflags=0): recover=0, dbflags=0):
"""bsdTableDB(filename, dbhome, create=0, truncate=0, mode=0600) """bsdTableDB(filename, dbhome, create=0, truncate=0, mode=0o600)
Open database name in the dbhome BerkeleyDB directory. Open database name in the dbhome BerkeleyDB directory.
Use keyword arguments when calling this constructor. Use keyword arguments when calling this constructor.

View File

@ -18,4 +18,4 @@ env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL)
the_txn = env.txn_begin() the_txn = env.txn_begin()
map = db.DB(env) map = db.DB(env)
map.open('xxx.db', "p", db.DB_HASH, db.DB_CREATE, 0666, txn=the_txn) map.open('xxx.db', "p", db.DB_HASH, db.DB_CREATE, 0o666, txn=the_txn)

View File

@ -44,7 +44,7 @@ class BasicTestCase(unittest.TestCase):
dbtype = db.DB_UNKNOWN # must be set in derived class dbtype = db.DB_UNKNOWN # must be set in derived class
dbopenflags = 0 dbopenflags = 0
dbsetflags = 0 dbsetflags = 0
dbmode = 0660 dbmode = 0o660
dbname = None dbname = None
useEnv = 0 useEnv = 0
envflags = 0 envflags = 0

View File

@ -50,10 +50,10 @@ class DBEnvClosedEarlyCrash(unittest.TestCase):
dbenv = db.DBEnv() dbenv = db.DBEnv()
dbenv.open(self.homeDir, dbenv.open(self.homeDir,
db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL, db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL,
0666) 0o666)
d = db.DB(dbenv) d = db.DB(dbenv)
d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0666) d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0o666)
try: try:
dbenv.close() dbenv.close()
@ -75,10 +75,10 @@ class DBEnvClosedEarlyCrash(unittest.TestCase):
dbenv = db.DBEnv() dbenv = db.DBEnv()
dbenv.open(self.homeDir, dbenv.open(self.homeDir,
db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL, db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL,
0666) 0o666)
d = db.DB(dbenv) d = db.DB(dbenv)
d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0666) d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0o666)
try: try:
dbenv.close() dbenv.close()

View File

@ -26,9 +26,9 @@ class DBSequenceTest(unittest.TestCase):
tempfile.tempdir = None tempfile.tempdir = None
self.dbenv = db.DBEnv() self.dbenv = db.DBEnv()
self.dbenv.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL, 0666) self.dbenv.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL, 0o666)
self.d = db.DB(self.dbenv) self.d = db.DB(self.dbenv)
self.d.open(self.filename, db.DB_BTREE, db.DB_CREATE, 0666) self.d.open(self.filename, db.DB_BTREE, db.DB_CREATE, 0o666)
def tearDown(self): def tearDown(self):
if hasattr(self, 'seq'): if hasattr(self, 'seq'):

View File

@ -4,6 +4,13 @@ from _collections import deque, defaultdict
from operator import itemgetter as _itemgetter from operator import itemgetter as _itemgetter
import sys as _sys import sys as _sys
# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
# They should however be considered an integral part of collections.py.
from _abcoll import *
import _abcoll
__all__ += _abcoll.__all__
def NamedTuple(typename, s): def NamedTuple(typename, s):
"""Returns a new subclass of tuple with named fields. """Returns a new subclass of tuple with named fields.

View File

@ -149,7 +149,7 @@ class py_object(_SimpleCData):
_type_ = "O" _type_ = "O"
def __repr__(self): def __repr__(self):
try: try:
return super(py_object, self).__repr__() return super().__repr__()
except ValueError: except ValueError:
return "%s(<NULL>)" % type(self).__name__ return "%s(<NULL>)" % type(self).__name__
_check_size(py_object, "P") _check_size(py_object, "P")

View File

@ -29,7 +29,7 @@ class _swapped_meta(type(Structure)):
rest = desc[2:] rest = desc[2:]
fields.append((name, _other_endian(typ)) + rest) fields.append((name, _other_endian(typ)) + rest)
value = fields value = fields
super(_swapped_meta, self).__setattr__(attrname, value) super().__setattr__(attrname, value)
################################################################ ################################################################

View File

@ -7,7 +7,7 @@ class X(Structure):
new_was_called = False new_was_called = False
def __new__(cls): def __new__(cls):
result = super(X, cls).__new__(cls) result = super().__new__(cls)
result.new_was_called = True result.new_was_called = True
return result return result

View File

@ -117,7 +117,10 @@ class NumberTestCase(unittest.TestCase):
def test_sizes(self): def test_sizes(self):
for t in signed_types + unsigned_types + float_types + bool_types: for t in signed_types + unsigned_types + float_types + bool_types:
size = struct.calcsize(t._type_) try:
size = struct.calcsize(t._type_)
except struct.error:
continue
# sizeof of the type... # sizeof of the type...
self.failUnlessEqual(sizeof(t), size) self.failUnlessEqual(sizeof(t), size)
# and sizeof of an instance # and sizeof of an instance

View File

@ -12,5 +12,5 @@ __all__ = ["error","open"]
error = bsddb.error # Exported for anydbm error = bsddb.error # Exported for anydbm
def open(file, flag = 'r', mode=0666): def open(file, flag = 'r', mode=0o666):
return bsddb.hashopen(file, flag, mode) return bsddb.hashopen(file, flag, mode)

View File

@ -1040,7 +1040,7 @@ main (int argc, char **argv) {
def move_file (self, src, dst): def move_file (self, src, dst):
return move_file (src, dst, dry_run=self.dry_run) return move_file (src, dst, dry_run=self.dry_run)
def mkpath (self, name, mode=0777): def mkpath (self, name, mode=0o777):
mkpath (name, mode, self.dry_run) mkpath (name, mode, self.dry_run)

View File

@ -356,7 +356,7 @@ class Command:
util.execute(func, args, msg, dry_run=self.dry_run) util.execute(func, args, msg, dry_run=self.dry_run)
def mkpath (self, name, mode=0777): def mkpath (self, name, mode=0o777):
dir_util.mkpath(name, mode, dry_run=self.dry_run) dir_util.mkpath(name, mode, dry_run=self.dry_run)

View File

@ -114,7 +114,9 @@ class build_py (Command):
build_dir = os.path.join(*([self.build_lib] + package.split('.'))) build_dir = os.path.join(*([self.build_lib] + package.split('.')))
# Length of path to strip from found files # Length of path to strip from found files
plen = len(src_dir)+1 plen = 0
if src_dir:
plen = len(src_dir)+1
# Strip directory from globbed filenames # Strip directory from globbed filenames
filenames = [ filenames = [

View File

@ -119,8 +119,8 @@ class build_scripts (Command):
if self.dry_run: if self.dry_run:
log.info("changing mode of %s", file) log.info("changing mode of %s", file)
else: else:
oldmode = os.stat(file)[ST_MODE] & 07777 oldmode = os.stat(file)[ST_MODE] & 0o7777
newmode = (oldmode | 0555) & 07777 newmode = (oldmode | 0o555) & 0o7777
if newmode != oldmode: if newmode != oldmode:
log.info("changing mode of %s from %o to %o", log.info("changing mode of %s from %o to %o",
file, oldmode, newmode) file, oldmode, newmode)

View File

@ -53,7 +53,7 @@ class install_scripts (Command):
if self.dry_run: if self.dry_run:
log.info("changing mode of %s", file) log.info("changing mode of %s", file)
else: else:
mode = ((os.stat(file)[ST_MODE]) | 0555) & 07777 mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777
log.info("changing mode of %s to %o", file, mode) log.info("changing mode of %s to %o", file, mode)
os.chmod(file, mode) os.chmod(file, mode)

View File

@ -183,7 +183,7 @@ Your selection [default 1]: ''', end=' ')
username, password)) username, password))
f.close() f.close()
try: try:
os.chmod(rc, 0600) os.chmod(rc, 0o600)
except: except:
pass pass
elif choice == '2': elif choice == '2':

View File

@ -18,7 +18,7 @@ _path_created = {}
# I don't use os.makedirs because a) it's new to Python 1.5.2, and # I don't use os.makedirs because a) it's new to Python 1.5.2, and
# b) it blows up if the directory already exists (I want to silently # b) it blows up if the directory already exists (I want to silently
# succeed in that case). # succeed in that case).
def mkpath (name, mode=0777, verbose=0, dry_run=0): def mkpath (name, mode=0o777, verbose=0, dry_run=0):
"""Create a directory and any missing ancestor directories. If the """Create a directory and any missing ancestor directories. If the
directory already exists (or if 'name' is the empty string, which directory already exists (or if 'name' is the empty string, which
means the current directory, which of course exists), then do means the current directory, which of course exists), then do
@ -85,7 +85,7 @@ def mkpath (name, mode=0777, verbose=0, dry_run=0):
# mkpath () # mkpath ()
def create_tree (base_dir, files, mode=0777, verbose=0, dry_run=0): def create_tree (base_dir, files, mode=0o777, verbose=0, dry_run=0):
"""Create all the empty directories under 'base_dir' needed to """Create all the empty directories under 'base_dir' needed to
put 'files' there. 'base_dir' is just the a name of a directory put 'files' there. 'base_dir' is just the a name of a directory

View File

@ -18,7 +18,6 @@ from distutils.ccompiler import \
import distutils.util import distutils.util
import distutils.dir_util import distutils.dir_util
from distutils import log from distutils import log
import mkcwproject
class MWerksCompiler (CCompiler) : class MWerksCompiler (CCompiler) :
"""Concrete class that implements an interface to MetroWerks CodeWarrior, """Concrete class that implements an interface to MetroWerks CodeWarrior,
@ -188,6 +187,7 @@ class MWerksCompiler (CCompiler) :
# doesn't have a clue about our working directory. # doesn't have a clue about our working directory.
xmlfilename = os.path.join(os.getcwd(), os.path.join(build_temp, xmlname)) xmlfilename = os.path.join(os.getcwd(), os.path.join(build_temp, xmlname))
log.debug("\tCreate XML file %s", xmlfilename) log.debug("\tCreate XML file %s", xmlfilename)
import mkcwproject
xmlbuilder = mkcwproject.cwxmlgen.ProjectBuilder(settings) xmlbuilder = mkcwproject.cwxmlgen.ProjectBuilder(settings)
xmlbuilder.generate() xmlbuilder.generate()
xmldata = settings['tmp_projectxmldata'] xmldata = settings['tmp_projectxmldata']

View File

@ -9,12 +9,12 @@ from distutils import log
class LoggingSilencer(object): class LoggingSilencer(object):
def setUp(self): def setUp(self):
super(LoggingSilencer, self).setUp() super().setUp()
self.threshold = log.set_threshold(log.FATAL) self.threshold = log.set_threshold(log.FATAL)
def tearDown(self): def tearDown(self):
log.set_threshold(self.threshold) log.set_threshold(self.threshold)
super(LoggingSilencer, self).tearDown() super().tearDown()
class TempdirManager(object): class TempdirManager(object):
@ -24,11 +24,11 @@ class TempdirManager(object):
""" """
def setUp(self): def setUp(self):
super(TempdirManager, self).setUp() super().setUp()
self.tempdirs = [] self.tempdirs = []
def tearDown(self): def tearDown(self):
super(TempdirManager, self).tearDown() super().tearDown()
while self.tempdirs: while self.tempdirs:
d = self.tempdirs.pop() d = self.tempdirs.pop()
shutil.rmtree(d) shutil.rmtree(d)

View File

@ -1,10 +1,13 @@
"""Tests for distutils.command.build_py.""" """Tests for distutils.command.build_py."""
import os import os
import sys
import StringIO
import unittest import unittest
from distutils.command.build_py import build_py from distutils.command.build_py import build_py
from distutils.core import Distribution from distutils.core import Distribution
from distutils.errors import DistutilsFileError
from distutils.tests import support from distutils.tests import support
@ -53,6 +56,38 @@ class BuildPyTestCase(support.TempdirManager,
self.assert_("__init__.pyc" in files) self.assert_("__init__.pyc" in files)
self.assert_("README.txt" in files) self.assert_("README.txt" in files)
def test_empty_package_dir (self):
# See SF 1668596/1720897.
cwd = os.getcwd()
# create the distribution files.
sources = self.mkdtemp()
open(os.path.join(sources, "__init__.py"), "w").close()
testdir = os.path.join(sources, "doc")
os.mkdir(testdir)
open(os.path.join(testdir, "testfile"), "w").close()
os.chdir(sources)
sys.stdout = StringIO.StringIO()
try:
dist = Distribution({"packages": ["pkg"],
"package_dir": {"pkg": ""},
"package_data": {"pkg": ["doc/*"]}})
# script_name need not exist, it just need to be initialized
dist.script_name = os.path.join(sources, "setup.py")
dist.script_args = ["build"]
dist.parse_command_line()
try:
dist.run_commands()
except DistutilsFileError:
self.fail("failed package_data test when package_dir is ''")
finally:
# Restore state.
os.chdir(cwd)
sys.stdout = sys.__stdout__
def test_suite(): def test_suite():
return unittest.makeSuite(BuildPyTestCase) return unittest.makeSuite(BuildPyTestCase)

View File

@ -220,7 +220,7 @@ class _Database(UserDict.DictMixin):
self._os.chmod(file, self._mode) self._os.chmod(file, self._mode)
def open(file, flag=None, mode=0666): def open(file, flag=None, mode=0o666):
"""Open the database file, filename, and return corresponding object. """Open the database file, filename, and return corresponding object.
The flag argument, used to control how the database is opened in the The flag argument, used to control how the database is opened in the
@ -229,7 +229,7 @@ def open(file, flag=None, mode=0666):
not exist. not exist.
The optional mode argument is the UNIX mode of the file, used only when The optional mode argument is the UNIX mode of the file, used only when
the database has to be created. It defaults to octal code 0666 (and the database has to be created. It defaults to octal code 0o666 (and
will be modified by the prevailing umask). will be modified by the prevailing umask).
""" """

View File

@ -319,9 +319,7 @@ class FTP:
size = None size = None
if self.passiveserver: if self.passiveserver:
host, port = self.makepasv() host, port = self.makepasv()
af, socktype, proto, canon, sa = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0] conn = socket.create_connection((host, port), self.timeout)
conn = socket.socket(af, socktype, proto)
conn.connect(sa)
if rest is not None: if rest is not None:
self.sendcmd("REST %s" % rest) self.sendcmd("REST %s" % rest)
resp = self.sendcmd(cmd) resp = self.sendcmd(cmd)

View File

@ -476,7 +476,7 @@ def _os_path_isdir(pathname):
s = _os_stat(pathname) s = _os_stat(pathname)
except OSError: except OSError:
return None return None
return (s.st_mode & 0170000) == 0040000 return (s.st_mode & 0o170000) == 0o040000
def _timestamp(pathname): def _timestamp(pathname):
"Return the file modification time as a Long." "Return the file modification time as a Long."

View File

@ -227,10 +227,10 @@ class Maildir(Mailbox):
Mailbox.__init__(self, dirname, factory, create) Mailbox.__init__(self, dirname, factory, create)
if not os.path.exists(self._path): if not os.path.exists(self._path):
if create: if create:
os.mkdir(self._path, 0700) os.mkdir(self._path, 0o700)
os.mkdir(os.path.join(self._path, 'tmp'), 0700) os.mkdir(os.path.join(self._path, 'tmp'), 0o700)
os.mkdir(os.path.join(self._path, 'new'), 0700) os.mkdir(os.path.join(self._path, 'new'), 0o700)
os.mkdir(os.path.join(self._path, 'cur'), 0700) os.mkdir(os.path.join(self._path, 'cur'), 0o700)
else: else:
raise NoSuchMailboxError(self._path) raise NoSuchMailboxError(self._path)
self._toc = {} self._toc = {}
@ -802,9 +802,9 @@ class MH(Mailbox):
Mailbox.__init__(self, path, factory, create) Mailbox.__init__(self, path, factory, create)
if not os.path.exists(self._path): if not os.path.exists(self._path):
if create: if create:
os.mkdir(self._path, 0700) os.mkdir(self._path, 0o700)
os.close(os.open(os.path.join(self._path, '.mh_sequences'), os.close(os.open(os.path.join(self._path, '.mh_sequences'),
os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600)) os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
else: else:
raise NoSuchMailboxError(self._path) raise NoSuchMailboxError(self._path)
self._locked = False self._locked = False

View File

@ -67,7 +67,7 @@ s = m.getbodytext(0) # text of message's body, not decoded
MH_PROFILE = '~/.mh_profile' MH_PROFILE = '~/.mh_profile'
PATH = '~/Mail' PATH = '~/Mail'
MH_SEQUENCES = '.mh_sequences' MH_SEQUENCES = '.mh_sequences'
FOLDER_PROTECT = 0700 FOLDER_PROTECT = 0o700
# Imported modules # Imported modules

147
Lib/os.py
View File

@ -147,8 +147,8 @@ SEEK_END = 2
# Super directory utilities. # Super directory utilities.
# (Inspired by Eric Raymond; the doc strings are mostly his) # (Inspired by Eric Raymond; the doc strings are mostly his)
def makedirs(name, mode=0777): def makedirs(name, mode=0o777):
"""makedirs(path [, mode=0777]) """makedirs(path [, mode=0o777])
Super-mkdir; create a leaf directory and all intermediate ones. Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not Works like mkdir, except that any intermediate path segment (not
@ -405,108 +405,63 @@ def _execvpe(file, args, env=None):
raise error, saved_exc, saved_tb raise error, saved_exc, saved_tb
raise error, last_exc, tb raise error, last_exc, tb
# Change environ to automatically call putenv() if it exists
try: if name == "riscos":
# This will fail if there's no putenv # On RISC OS, all env access goes through getenv and putenv
putenv from riscosenviron import _Environ
except NameError:
pass
else: else:
import UserDict # Change environ to automatically call putenv(), unsetenv if they exist.
from _abcoll import MutableMapping # Can't use collections (bootstrap)
# Fake unsetenv() for Windows class _Environ(MutableMapping):
# not sure about os2 here but def __init__(self, environ, keymap, putenv, unsetenv):
# I'm guessing they are the same. self.keymap = keymap
self.putenv = putenv
self.unsetenv = unsetenv
self.data = data = {}
for key, value in environ.items():
data[keymap(key)] = value
def __getitem__(self, key):
return self.data[self.keymap(key)]
def __setitem__(self, key, item):
self.putenv(key, item)
self.data[self.keymap(key)] = item
def __delitem__(self, key):
self.unsetenv(key)
del self.data[self.keymap(key)]
def __iter__(self):
for key in self.data:
yield key
def __len__(self):
return len(self.data)
def copy(self):
return dict(self)
def setdefault(self, key, value):
if key not in self:
self[key] = value
return self[key]
if name in ('os2', 'nt'): try:
def unsetenv(key): _putenv = putenv
putenv(key, "") except NameError:
_putenv = lambda key, value: None
else:
__all__.append("putenv")
if name == "riscos": try:
# On RISC OS, all env access goes through getenv and putenv _unsetenv = unsetenv
from riscosenviron import _Environ except NameError:
elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE _unsetenv = lambda key: _putenv(key, "")
# But we store them as upper case else:
class _Environ(UserDict.IterableUserDict): __all__.append("unsetenv")
def __init__(self, environ):
UserDict.UserDict.__init__(self)
data = self.data
for k, v in environ.items():
data[k.upper()] = v
def __setitem__(self, key, item):
putenv(key, item)
self.data[key.upper()] = item
def __getitem__(self, key):
return self.data[key.upper()]
try:
unsetenv
except NameError:
def __delitem__(self, key):
del self.data[key.upper()]
else:
def __delitem__(self, key):
unsetenv(key)
del self.data[key.upper()]
def __contains__(self, key):
return key.upper() in self.data
def get(self, key, failobj=None):
return self.data.get(key.upper(), failobj)
def update(self, dict=None, **kwargs):
if dict:
try:
keys = dict.keys()
except AttributeError:
# List of (key, value)
for k, v in dict:
self[k] = v
else:
# got keys
# cannot use items(), since mappings
# may not have them.
for k in keys:
self[k] = dict[k]
if kwargs:
self.update(kwargs)
def copy(self):
return dict(self)
if name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
_keymap = lambda key: key.upper()
else: # Where Env Var Names Can Be Mixed Case else: # Where Env Var Names Can Be Mixed Case
class _Environ(UserDict.IterableUserDict): _keymap = lambda key: key
def __init__(self, environ):
UserDict.UserDict.__init__(self)
self.data = environ
def __setitem__(self, key, item):
putenv(key, item)
self.data[key] = item
def update(self, dict=None, **kwargs):
if dict:
try:
keys = dict.keys()
except AttributeError:
# List of (key, value)
for k, v in dict:
self[k] = v
else:
# got keys
# cannot use items(), since mappings
# may not have them.
for k in keys:
self[k] = dict[k]
if kwargs:
self.update(kwargs)
try:
unsetenv
except NameError:
pass
else:
def __delitem__(self, key):
unsetenv(key)
del self.data[key]
def copy(self):
return dict(self)
environ = _Environ(environ, _keymap, _putenv, _unsetenv)
environ = _Environ(environ)
def getenv(key, default=None): def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist. """Get an environment variable, return None if it doesn't exist.

View File

@ -557,7 +557,7 @@ _DIRENT_H = 1
# Included from bits/dirent.h # Included from bits/dirent.h
def _D_ALLOC_NAMLEN(d): return (_D_EXACT_NAMLEN (d) + 1) def _D_ALLOC_NAMLEN(d): return (_D_EXACT_NAMLEN (d) + 1)
def IFTODT(mode): return (((mode) & 0170000) >> 12) def IFTODT(mode): return (((mode) & 0o170000) >> 12)
def DTTOIF(dirtype): return ((dirtype) << 12) def DTTOIF(dirtype): return ((dirtype) << 12)
@ -567,17 +567,17 @@ MAXNAMLEN = NAME_MAX
MAXNAMLEN = 255 MAXNAMLEN = 255
# Included from posix/stat.h # Included from posix/stat.h
S_IFMT = 00170000 S_IFMT = 0o0170000
S_IFSOCK = 0140000 S_IFSOCK = 0o140000
S_IFLNK = 0120000 S_IFLNK = 0o120000
S_IFREG = 0100000 S_IFREG = 0o100000
S_IFBLK = 0060000 S_IFBLK = 0o060000
S_IFDIR = 0040000 S_IFDIR = 0o040000
S_IFCHR = 0020000 S_IFCHR = 0o020000
S_IFIFO = 0010000 S_IFIFO = 0o010000
S_ISUID = 0004000 S_ISUID = 0o004000
S_ISGID = 0002000 S_ISGID = 0o002000
S_ISVTX = 0001000 S_ISVTX = 0o001000
def S_ISLNK(m): return (((m) & S_IFMT) == S_IFLNK) def S_ISLNK(m): return (((m) & S_IFMT) == S_IFLNK)
def S_ISREG(m): return (((m) & S_IFMT) == S_IFREG) def S_ISREG(m): return (((m) & S_IFMT) == S_IFREG)
@ -592,18 +592,18 @@ def S_ISFIFO(m): return (((m) & S_IFMT) == S_IFIFO)
def S_ISSOCK(m): return (((m) & S_IFMT) == S_IFSOCK) def S_ISSOCK(m): return (((m) & S_IFMT) == S_IFSOCK)
S_IRWXU = 00700 S_IRWXU = 0o0700
S_IRUSR = 00400 S_IRUSR = 0o0400
S_IWUSR = 00200 S_IWUSR = 0o0200
S_IXUSR = 00100 S_IXUSR = 0o0100
S_IRWXG = 00070 S_IRWXG = 0o0070
S_IRGRP = 00040 S_IRGRP = 0o0040
S_IWGRP = 00020 S_IWGRP = 0o0020
S_IXGRP = 00010 S_IXGRP = 0o0010
S_IRWXO = 00007 S_IRWXO = 0o0007
S_IROTH = 00004 S_IROTH = 0o0004
S_IWOTH = 00002 S_IWOTH = 0o0002
S_IXOTH = 00001 S_IXOTH = 0o0001
S_IRWXUGO = (S_IRWXU|S_IRWXG|S_IRWXO) S_IRWXUGO = (S_IRWXU|S_IRWXG|S_IRWXO)
S_IALLUGO = (S_ISUID|S_ISGID|S_ISVTX|S_IRWXUGO) S_IALLUGO = (S_ISUID|S_ISGID|S_ISVTX|S_IRWXUGO)
S_IRUGO = (S_IRUSR|S_IRGRP|S_IROTH) S_IRUGO = (S_IRUSR|S_IRGRP|S_IROTH)
@ -612,24 +612,24 @@ S_IXUGO = (S_IXUSR|S_IXGRP|S_IXOTH)
_STAT_VER_KERNEL = 0 _STAT_VER_KERNEL = 0
# Included from posix/fcntl.h # Included from posix/fcntl.h
O_ACCMODE = 0003 O_ACCMODE = 0o003
O_RWMASK = O_ACCMODE O_RWMASK = O_ACCMODE
O_RDONLY = 00 O_RDONLY = 00
O_WRONLY = 01 O_WRONLY = 0o1
O_RDWR = 02 O_RDWR = 0o2
O_CREAT = 0100 O_CREAT = 0o100
O_EXCL = 0200 O_EXCL = 0o200
O_NOCTTY = 0400 O_NOCTTY = 0o400
O_TRUNC = 01000 O_TRUNC = 0o1000
O_APPEND = 02000 O_APPEND = 0o2000
O_NONBLOCK = 04000 O_NONBLOCK = 0o4000
O_NDELAY = O_NONBLOCK O_NDELAY = O_NONBLOCK
O_SYNC = 010000 O_SYNC = 0o10000
O_FSYNC = O_SYNC O_FSYNC = O_SYNC
O_ASYNC = 020000 O_ASYNC = 0o20000
FASYNC = O_ASYNC FASYNC = O_ASYNC
O_DIRECTORY = 040000 O_DIRECTORY = 0o40000
O_NOTRAVERSE = 0100000 O_NOTRAVERSE = 0o100000
O_NOFOLLOW = O_NOTRAVERSE O_NOFOLLOW = O_NOTRAVERSE
F_DUPFD = 0 F_DUPFD = 0
F_GETFD = 1 F_GETFD = 1

View File

@ -100,10 +100,10 @@ def pack(x, forcetype = None):
data = data[2:] data = data[2:]
return AE.AECreateDesc('utxt', data) return AE.AECreateDesc('utxt', data)
if isinstance(x, list): if isinstance(x, list):
list = AE.AECreateList('', 0) lst = AE.AECreateList('', 0)
for item in x: for item in x:
list.AEPutDesc(0, pack(item)) lst.AEPutDesc(0, pack(item))
return list return lst
if isinstance(x, dict): if isinstance(x, dict):
record = AE.AECreateList('', 1) record = AE.AECreateList('', 1)
for key, value in x.items(): for key, value in x.items():

View File

@ -504,7 +504,7 @@ class AppBuilder(BundleBuilder):
standalone = self.standalone standalone = self.standalone
semi_standalone = self.semi_standalone semi_standalone = self.semi_standalone
open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals()) open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
os.chmod(bootstrappath, 0775) os.chmod(bootstrappath, 0o775)
if self.iconfile is not None: if self.iconfile is not None:
iconbase = os.path.basename(self.iconfile) iconbase = os.path.basename(self.iconfile)
@ -603,7 +603,7 @@ class AppBuilder(BundleBuilder):
walk(path) walk(path)
else: else:
mod = os.stat(path)[stat.ST_MODE] mod = os.stat(path)[stat.ST_MODE]
if not (mod & 0100): if not (mod & 0o100):
continue continue
relpath = path[len(self.bundlepath):] relpath = path[len(self.bundlepath):]
self.message("Stripping %s" % relpath, 2) self.message("Stripping %s" % relpath, 2)

View File

@ -61,7 +61,7 @@ def mkdirs(dst):
if os.sep == ':' and not ':' in head: if os.sep == ':' and not ':' in head:
head = head + ':' head = head + ':'
mkdirs(head) mkdirs(head)
os.mkdir(dst, 0777) os.mkdir(dst, 0o777)
def touched(dst): def touched(dst):
"""Tell the finder a file has changed. No-op on MacOSX.""" """Tell the finder a file has changed. No-op on MacOSX."""

View File

@ -320,7 +320,7 @@ class Dict(_InternalDict):
from warnings import warn from warnings import warn
warn("The plistlib.Dict class is deprecated, use builtin dict instead", warn("The plistlib.Dict class is deprecated, use builtin dict instead",
PendingDeprecationWarning) PendingDeprecationWarning)
super(Dict, self).__init__(**kwargs) super().__init__(**kwargs)
class Plist(_InternalDict): class Plist(_InternalDict):
@ -333,7 +333,7 @@ class Plist(_InternalDict):
from warnings import warn from warnings import warn
warn("The Plist class is deprecated, use the readPlist() and " warn("The Plist class is deprecated, use the readPlist() and "
"writePlist() functions instead", PendingDeprecationWarning) "writePlist() functions instead", PendingDeprecationWarning)
super(Plist, self).__init__(**kwargs) super().__init__(**kwargs)
def fromFile(cls, pathOrFile): def fromFile(cls, pathOrFile):
"""Deprecated. Use the readPlist() function instead.""" """Deprecated. Use the readPlist() function instead."""

View File

@ -97,7 +97,7 @@ NGROUPS_MAX_DEFAULT = 16
NZERO = 20 NZERO = 20
NULL = 0 NULL = 0
NULL = 0 NULL = 0
CMASK = 022 CMASK = 0o22
CDLIMIT = (1<<11) CDLIMIT = (1<<11)
NBPS = 0x20000 NBPS = 0x20000
NBPSCTR = 512 NBPSCTR = 512
@ -733,13 +733,13 @@ _SPARC_MAXREGWINDOW = 31
_XRS_ID = 0x78727300 _XRS_ID = 0x78727300
GETCONTEXT = 0 GETCONTEXT = 0
SETCONTEXT = 1 SETCONTEXT = 1
UC_SIGMASK = 001 UC_SIGMASK = 0o01
UC_STACK = 002 UC_STACK = 0o02
UC_CPU = 004 UC_CPU = 0o04
UC_MAU = 010 UC_MAU = 0o10
UC_FPU = UC_MAU UC_FPU = UC_MAU
UC_INTR = 020 UC_INTR = 0o20
UC_ASR = 040 UC_ASR = 0o40
UC_MCONTEXT = (UC_CPU|UC_FPU|UC_ASR) UC_MCONTEXT = (UC_CPU|UC_FPU|UC_ASR)
UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT) UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT)
_SIGQUEUE_MAX = 32 _SIGQUEUE_MAX = 32
@ -1021,14 +1021,14 @@ AT_STAT = (AT_MODE|AT_UID|AT_GID|AT_FSID|AT_NODEID|AT_NLINK|\
AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME) AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME)
AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\ AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\
AT_BLKSIZE|AT_NBLOCKS|AT_VCODE) AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
VSUID = 04000 VSUID = 0o4000
VSGID = 02000 VSGID = 0o2000
VSVTX = 01000 VSVTX = 0o1000
VREAD = 00400 VREAD = 0o0400
VWRITE = 00200 VWRITE = 0o0200
VEXEC = 00100 VEXEC = 0o0100
MODEMASK = 07777 MODEMASK = 0o7777
PERMMASK = 00777 PERMMASK = 0o0777
def MANDMODE(mode): return (((mode) & (VSGID|(VEXEC>>3))) == VSGID) def MANDMODE(mode): return (((mode) & (VSGID|(VEXEC>>3))) == VSGID)
VSA_ACL = 0x0001 VSA_ACL = 0x0001

View File

@ -94,7 +94,7 @@ NGROUPS_MAX_DEFAULT = 16
NZERO = 20 NZERO = 20
NULL = 0 NULL = 0
NULL = 0 NULL = 0
CMASK = 022 CMASK = 0o22
CDLIMIT = (1<<11) CDLIMIT = (1<<11)
NBPS = 0x20000 NBPS = 0x20000
NBPSCTR = 512 NBPSCTR = 512
@ -730,13 +730,13 @@ _SPARC_MAXREGWINDOW = 31
_XRS_ID = 0x78727300 _XRS_ID = 0x78727300
GETCONTEXT = 0 GETCONTEXT = 0
SETCONTEXT = 1 SETCONTEXT = 1
UC_SIGMASK = 001 UC_SIGMASK = 0o01
UC_STACK = 002 UC_STACK = 0o02
UC_CPU = 004 UC_CPU = 0o04
UC_MAU = 010 UC_MAU = 0o10
UC_FPU = UC_MAU UC_FPU = UC_MAU
UC_INTR = 020 UC_INTR = 0o20
UC_ASR = 040 UC_ASR = 0o40
UC_MCONTEXT = (UC_CPU|UC_FPU|UC_ASR) UC_MCONTEXT = (UC_CPU|UC_FPU|UC_ASR)
UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT) UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT)
_SIGQUEUE_MAX = 32 _SIGQUEUE_MAX = 32
@ -1400,14 +1400,14 @@ AT_STAT = (AT_MODE|AT_UID|AT_GID|AT_FSID|AT_NODEID|AT_NLINK|\
AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME) AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME)
AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\ AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\
AT_BLKSIZE|AT_NBLOCKS|AT_VCODE) AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
VSUID = 04000 VSUID = 0o4000
VSGID = 02000 VSGID = 0o2000
VSVTX = 01000 VSVTX = 0o1000
VREAD = 00400 VREAD = 0o0400
VWRITE = 00200 VWRITE = 0o0200
VEXEC = 00100 VEXEC = 0o0100
MODEMASK = 07777 MODEMASK = 0o7777
PERMMASK = 00777 PERMMASK = 0o0777
def MANDMODE(mode): return (((mode) & (VSGID|(VEXEC>>3))) == VSGID) def MANDMODE(mode): return (((mode) & (VSGID|(VEXEC>>3))) == VSGID)
VSA_ACL = 0x0001 VSA_ACL = 0x0001

View File

@ -187,8 +187,8 @@ NC_TPI_COTS = 2
NC_TPI_COTS_ORD = 3 NC_TPI_COTS_ORD = 3
NC_TPI_RAW = 4 NC_TPI_RAW = 4
NC_NOFLAG = 00 NC_NOFLAG = 00
NC_VISIBLE = 01 NC_VISIBLE = 0o1
NC_BROADCAST = 02 NC_BROADCAST = 0o2
NC_NOPROTOFMLY = "-" NC_NOPROTOFMLY = "-"
NC_LOOPBACK = "loopback" NC_LOOPBACK = "loopback"
NC_INET = "inet" NC_INET = "inet"

View File

@ -65,41 +65,41 @@ ES_PRVSETS = 6
ES_MACADTLID = 7 ES_MACADTLID = 7
ES_PRVID = 8 ES_PRVID = 8
ES_TPGETMAJOR = 9 ES_TPGETMAJOR = 9
SA_EXEC = 001 SA_EXEC = 0o01
SA_WRITE = 002 SA_WRITE = 0o02
SA_READ = 004 SA_READ = 0o04
SA_SUBSIZE = 010 SA_SUBSIZE = 0o10
# Included from sys/stropts_f.h # Included from sys/stropts_f.h
X_STR = (ord('S')<<8) X_STR = (ord('S')<<8)
X_I_BASE = (X_STR|0200) X_I_BASE = (X_STR|0o200)
X_I_NREAD = (X_STR|0201) X_I_NREAD = (X_STR|0o201)
X_I_PUSH = (X_STR|0202) X_I_PUSH = (X_STR|0o202)
X_I_POP = (X_STR|0203) X_I_POP = (X_STR|0o203)
X_I_LOOK = (X_STR|0204) X_I_LOOK = (X_STR|0o204)
X_I_FLUSH = (X_STR|0205) X_I_FLUSH = (X_STR|0o205)
X_I_SRDOPT = (X_STR|0206) X_I_SRDOPT = (X_STR|0o206)
X_I_GRDOPT = (X_STR|0207) X_I_GRDOPT = (X_STR|0o207)
X_I_STR = (X_STR|0210) X_I_STR = (X_STR|0o210)
X_I_SETSIG = (X_STR|0211) X_I_SETSIG = (X_STR|0o211)
X_I_GETSIG = (X_STR|0212) X_I_GETSIG = (X_STR|0o212)
X_I_FIND = (X_STR|0213) X_I_FIND = (X_STR|0o213)
X_I_LINK = (X_STR|0214) X_I_LINK = (X_STR|0o214)
X_I_UNLINK = (X_STR|0215) X_I_UNLINK = (X_STR|0o215)
X_I_PEEK = (X_STR|0217) X_I_PEEK = (X_STR|0o217)
X_I_FDINSERT = (X_STR|0220) X_I_FDINSERT = (X_STR|0o220)
X_I_SENDFD = (X_STR|0221) X_I_SENDFD = (X_STR|0o221)
X_I_RECVFD = (X_STR|0222) X_I_RECVFD = (X_STR|0o222)
# Included from unistd.h # Included from unistd.h
# Included from sys/unistd.h # Included from sys/unistd.h
R_OK = 004 R_OK = 0o04
W_OK = 002 W_OK = 0o02
X_OK = 001 X_OK = 0o01
F_OK = 000 F_OK = 000
EFF_ONLY_OK = 010 EFF_ONLY_OK = 0o10
EX_OK = 020 EX_OK = 0o20
SEEK_SET = 0 SEEK_SET = 0
SEEK_CUR = 1 SEEK_CUR = 1
SEEK_END = 2 SEEK_END = 2
@ -289,40 +289,40 @@ MUXID_ALL = (-1)
ANYMARK = 0x01 ANYMARK = 0x01
LASTMARK = 0x02 LASTMARK = 0x02
STR = (ord('S')<<8) STR = (ord('S')<<8)
I_NREAD = (STR|01) I_NREAD = (STR|0o1)
I_PUSH = (STR|02) I_PUSH = (STR|0o2)
I_POP = (STR|03) I_POP = (STR|0o3)
I_LOOK = (STR|04) I_LOOK = (STR|0o4)
I_FLUSH = (STR|05) I_FLUSH = (STR|0o5)
I_SRDOPT = (STR|06) I_SRDOPT = (STR|0o6)
I_GRDOPT = (STR|07) I_GRDOPT = (STR|0o7)
I_STR = (STR|010) I_STR = (STR|0o10)
I_SETSIG = (STR|011) I_SETSIG = (STR|0o11)
I_GETSIG = (STR|012) I_GETSIG = (STR|0o12)
I_FIND = (STR|013) I_FIND = (STR|0o13)
I_LINK = (STR|014) I_LINK = (STR|0o14)
I_UNLINK = (STR|015) I_UNLINK = (STR|0o15)
I_PEEK = (STR|017) I_PEEK = (STR|0o17)
I_FDINSERT = (STR|020) I_FDINSERT = (STR|0o20)
I_SENDFD = (STR|021) I_SENDFD = (STR|0o21)
I_RECVFD = (STR|022) I_RECVFD = (STR|0o22)
I_E_RECVFD = (STR|016) I_E_RECVFD = (STR|0o16)
I_RECVFD = (STR|016) I_RECVFD = (STR|0o16)
I_RECVFD = (STR|022) I_RECVFD = (STR|0o22)
I_SWROPT = (STR|023) I_SWROPT = (STR|0o23)
I_GWROPT = (STR|024) I_GWROPT = (STR|0o24)
I_LIST = (STR|025) I_LIST = (STR|0o25)
I_PLINK = (STR|026) I_PLINK = (STR|0o26)
I_PUNLINK = (STR|027) I_PUNLINK = (STR|0o27)
I_FLUSHBAND = (STR|034) I_FLUSHBAND = (STR|0o34)
I_CKBAND = (STR|035) I_CKBAND = (STR|0o35)
I_GETBAND = (STR|036) I_GETBAND = (STR|0o36)
I_ATMARK = (STR|037) I_ATMARK = (STR|0o37)
I_SETCLTIME = (STR|040) I_SETCLTIME = (STR|0o40)
I_GETCLTIME = (STR|041) I_GETCLTIME = (STR|0o41)
I_CANPUT = (STR|042) I_CANPUT = (STR|0o42)
I_S_RECVFD = (STR|043) I_S_RECVFD = (STR|0o43)
I_STATS = (STR|044) I_STATS = (STR|0o44)
I_BIGPIPE = (STR|045) I_BIGPIPE = (STR|0o45)
I_GETTP = (STR|046) I_GETTP = (STR|0o46)
INFTIM = -1 INFTIM = -1

View File

@ -242,7 +242,7 @@ _release_version = re.compile(r'([^0-9]+)'
_supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos', _supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos',
'mandrake', 'rocks', 'slackware', 'yellowdog', 'mandrake', 'rocks', 'slackware', 'yellowdog',
'gentoo', 'UnitedLinux') 'gentoo', 'UnitedLinux', 'turbolinux')
def _parse_release_file(firstline): def _parse_release_file(firstline):
@ -600,6 +600,16 @@ def win32_ver(release='',version='',csd='',ptype=''):
release = '2003Server' release = '2003Server'
else: else:
release = 'post2003' release = 'post2003'
elif maj == 6:
if min == 0:
# Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx
productType = GetVersionEx(1)[8]
if productType == 1: # VER_NT_WORKSTATION
release = 'Vista'
else:
release = '2008Server'
else:
release = 'post2008Server'
else: else:
if not release: if not release:
# E.g. Win3.1 with win32s # E.g. Win3.1 with win32s
@ -1064,6 +1074,16 @@ def uname():
# (_syscmd_ver() tends to return the vendor name as well) # (_syscmd_ver() tends to return the vendor name as well)
if system == 'Microsoft Windows': if system == 'Microsoft Windows':
system = 'Windows' system = 'Windows'
elif system == 'Microsoft' and release == 'Windows':
# Under Windows Vista and Windows Server 2008,
# Microsoft changed the output of the ver command. The
# release is no longer printed. This causes the
# system and release to be misidentified.
system = 'Windows'
if '6.0' == version[:3]:
release = 'Vista'
else:
release = ''
# In case we still don't know anything useful, we'll try to # In case we still don't know anything useful, we'll try to
# help ourselves # help ourselves

View File

@ -55,7 +55,7 @@ def _open_terminal():
pass pass
else: else:
try: try:
tty_name, master_fd = sgi._getpty(os.O_RDWR, 0666, 0) tty_name, master_fd = sgi._getpty(os.O_RDWR, 0o666, 0)
except IOError as msg: except IOError as msg:
raise os.error, msg raise os.error, msg
return master_fd, tty_name return master_fd, tty_name

View File

@ -110,19 +110,19 @@ class Random(_random.Random):
import time import time
a = int(time.time() * 256) # use fractional seconds a = int(time.time() * 256) # use fractional seconds
super(Random, self).seed(a) super().seed(a)
self.gauss_next = None self.gauss_next = None
def getstate(self): def getstate(self):
"""Return internal state; can be passed to setstate() later.""" """Return internal state; can be passed to setstate() later."""
return self.VERSION, super(Random, self).getstate(), self.gauss_next return self.VERSION, super().getstate(), self.gauss_next
def setstate(self, state): def setstate(self, state):
"""Restore internal state from object returned by getstate().""" """Restore internal state from object returned by getstate()."""
version = state[0] version = state[0]
if version == 2: if version == 2:
version, internalstate, self.gauss_next = state version, internalstate, self.gauss_next = state
super(Random, self).setstate(internalstate) super().setstate(internalstate)
else: else:
raise ValueError("state with version %s passed to " raise ValueError("state with version %s passed to "
"Random.setstate() of version %s" % "Random.setstate() of version %s" %

View File

@ -47,7 +47,7 @@ class Repr:
return '%s%s%s' % (left, s, right) return '%s%s%s' % (left, s, right)
def repr_tuple(self, x, level): def repr_tuple(self, x, level):
return self._repr_iterable(x, level, '(', ')', self.maxlist, ',') return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',')
def repr_list(self, x, level): def repr_list(self, x, level):
return self._repr_iterable(x, level, '[', ']', self.maxlist) return self._repr_iterable(x, level, '[', ']', self.maxlist)

View File

@ -40,12 +40,12 @@ class ModuleTests(unittest.TestCase):
sqlite.paramstyle) sqlite.paramstyle)
def CheckWarning(self): def CheckWarning(self):
self.assert_(issubclass(sqlite.Warning, StandardError), self.assert_(issubclass(sqlite.Warning, Exception),
"Warning is not a subclass of StandardError") "Warning is not a subclass of Exception")
def CheckError(self): def CheckError(self):
self.failUnless(issubclass(sqlite.Error, StandardError), self.failUnless(issubclass(sqlite.Error, Exception),
"Error is not a subclass of StandardError") "Error is not a subclass of Exception")
def CheckInterfaceError(self): def CheckInterfaceError(self):
self.failUnless(issubclass(sqlite.InterfaceError, sqlite.Error), self.failUnless(issubclass(sqlite.InterfaceError, sqlite.Error),

View File

@ -24,21 +24,21 @@ ST_CTIME = 9
# Extract bits from the mode # Extract bits from the mode
def S_IMODE(mode): def S_IMODE(mode):
return mode & 07777 return mode & 0o7777
def S_IFMT(mode): def S_IFMT(mode):
return mode & 0170000 return mode & 0o170000
# Constants used as S_IFMT() for various file types # Constants used as S_IFMT() for various file types
# (not all are implemented on all systems) # (not all are implemented on all systems)
S_IFDIR = 0040000 S_IFDIR = 0o040000
S_IFCHR = 0020000 S_IFCHR = 0o020000
S_IFBLK = 0060000 S_IFBLK = 0o060000
S_IFREG = 0100000 S_IFREG = 0o100000
S_IFIFO = 0010000 S_IFIFO = 0o010000
S_IFLNK = 0120000 S_IFLNK = 0o120000
S_IFSOCK = 0140000 S_IFSOCK = 0o140000
# Functions to test for each file type # Functions to test for each file type
@ -65,25 +65,25 @@ def S_ISSOCK(mode):
# Names for permission bits # Names for permission bits
S_ISUID = 04000 S_ISUID = 0o4000
S_ISGID = 02000 S_ISGID = 0o2000
S_ENFMT = S_ISGID S_ENFMT = S_ISGID
S_ISVTX = 01000 S_ISVTX = 0o1000
S_IREAD = 00400 S_IREAD = 0o0400
S_IWRITE = 00200 S_IWRITE = 0o0200
S_IEXEC = 00100 S_IEXEC = 0o0100
S_IRWXU = 00700 S_IRWXU = 0o0700
S_IRUSR = 00400 S_IRUSR = 0o0400
S_IWUSR = 00200 S_IWUSR = 0o0200
S_IXUSR = 00100 S_IXUSR = 0o0100
S_IRWXG = 00070 S_IRWXG = 0o0070
S_IRGRP = 00040 S_IRGRP = 0o0040
S_IWGRP = 00020 S_IWGRP = 0o0020
S_IXGRP = 00010 S_IXGRP = 0o0010
S_IRWXO = 00007 S_IRWXO = 0o0007
S_IROTH = 00004 S_IROTH = 0o0004
S_IWOTH = 00002 S_IWOTH = 0o0002
S_IXOTH = 00001 S_IXOTH = 0o0001
# Names for file flags # Names for file flags

View File

@ -141,26 +141,26 @@ PAX_NUMBER_FIELDS = {
#--------------------------------------------------------- #---------------------------------------------------------
# Bits used in the mode field, values in octal. # Bits used in the mode field, values in octal.
#--------------------------------------------------------- #---------------------------------------------------------
S_IFLNK = 0120000 # symbolic link S_IFLNK = 0o120000 # symbolic link
S_IFREG = 0100000 # regular file S_IFREG = 0o100000 # regular file
S_IFBLK = 0060000 # block device S_IFBLK = 0o060000 # block device
S_IFDIR = 0040000 # directory S_IFDIR = 0o040000 # directory
S_IFCHR = 0020000 # character device S_IFCHR = 0o020000 # character device
S_IFIFO = 0010000 # fifo S_IFIFO = 0o010000 # fifo
TSUID = 04000 # set UID on execution TSUID = 0o4000 # set UID on execution
TSGID = 02000 # set GID on execution TSGID = 0o2000 # set GID on execution
TSVTX = 01000 # reserved TSVTX = 0o1000 # reserved
TUREAD = 0400 # read by owner TUREAD = 0o400 # read by owner
TUWRITE = 0200 # write by owner TUWRITE = 0o200 # write by owner
TUEXEC = 0100 # execute/search by owner TUEXEC = 0o100 # execute/search by owner
TGREAD = 0040 # read by group TGREAD = 0o040 # read by group
TGWRITE = 0020 # write by group TGWRITE = 0o020 # write by group
TGEXEC = 0010 # execute/search by group TGEXEC = 0o010 # execute/search by group
TOREAD = 0004 # read by other TOREAD = 0o004 # read by other
TOWRITE = 0002 # write by other TOWRITE = 0o002 # write by other
TOEXEC = 0001 # execute/search by other TOEXEC = 0o001 # execute/search by other
#--------------------------------------------------------- #---------------------------------------------------------
# initialization # initialization
@ -192,7 +192,7 @@ def nti(s):
""" """
# There are two possible encodings for a number field, see # There are two possible encodings for a number field, see
# itn() below. # itn() below.
if s[0] != chr(0200): if s[0] != chr(0o200):
try: try:
n = int(nts(s) or "0", 8) n = int(nts(s) or "0", 8)
except ValueError: except ValueError:
@ -210,7 +210,7 @@ def itn(n, digits=8, format=DEFAULT_FORMAT):
# POSIX 1003.1-1988 requires numbers to be encoded as a string of # POSIX 1003.1-1988 requires numbers to be encoded as a string of
# octal digits followed by a null-byte, this allows values up to # octal digits followed by a null-byte, this allows values up to
# (8**(digits-1))-1. GNU tar allows storing numbers greater than # (8**(digits-1))-1. GNU tar allows storing numbers greater than
# that if necessary. A leading 0200 byte indicates this particular # that if necessary. A leading 0o200 byte indicates this particular
# encoding, the following digits-1 bytes are a big-endian # encoding, the following digits-1 bytes are a big-endian
# representation. This allows values up to (256**(digits-1))-1. # representation. This allows values up to (256**(digits-1))-1.
if 0 <= n < 8 ** (digits - 1): if 0 <= n < 8 ** (digits - 1):
@ -226,9 +226,9 @@ def itn(n, digits=8, format=DEFAULT_FORMAT):
s = "" s = ""
for i in range(digits - 1): for i in range(digits - 1):
s = chr(n & 0377) + s s = chr(n & 0o377) + s
n >>= 8 n >>= 8
s = chr(0200) + s s = chr(0o200) + s
return s return s
def uts(s, encoding, errors): def uts(s, encoding, errors):
@ -920,7 +920,7 @@ class TarInfo(object):
of the member. of the member.
""" """
self.name = name # member name self.name = name # member name
self.mode = 0644 # file permissions self.mode = 0o644 # file permissions
self.uid = 0 # user id self.uid = 0 # user id
self.gid = 0 # group id self.gid = 0 # group id
self.size = 0 # file size self.size = 0 # file size
@ -960,7 +960,7 @@ class TarInfo(object):
""" """
info = { info = {
"name": normpath(self.name), "name": normpath(self.name),
"mode": self.mode & 07777, "mode": self.mode & 0o7777,
"uid": self.uid, "uid": self.uid,
"gid": self.gid, "gid": self.gid,
"size": self.size, "size": self.size,
@ -1103,7 +1103,7 @@ class TarInfo(object):
""" """
parts = [ parts = [
stn(info.get("name", ""), 100), stn(info.get("name", ""), 100),
itn(info.get("mode", 0) & 07777, 8, format), itn(info.get("mode", 0) & 0o7777, 8, format),
itn(info.get("uid", 0), 8, format), itn(info.get("uid", 0), 8, format),
itn(info.get("gid", 0), 8, format), itn(info.get("gid", 0), 8, format),
itn(info.get("size", 0), 12, format), itn(info.get("size", 0), 12, format),
@ -2019,7 +2019,7 @@ class TarFile(object):
# Extract directory with a safe mode, so that # Extract directory with a safe mode, so that
# all files below can be extracted as well. # all files below can be extracted as well.
try: try:
os.makedirs(os.path.join(path, tarinfo.name), 0700) os.makedirs(os.path.join(path, tarinfo.name), 0o700)
except EnvironmentError: except EnvironmentError:
pass pass
directories.append(tarinfo) directories.append(tarinfo)

View File

@ -197,7 +197,7 @@ def _get_default_tempdir():
name = next(namer) name = next(namer)
filename = _os.path.join(dir, name) filename = _os.path.join(dir, name)
try: try:
fd = _os.open(filename, flags, 0600) fd = _os.open(filename, flags, 0o600)
fp = _os.fdopen(fd, 'w') fp = _os.fdopen(fd, 'w')
fp.write('blat') fp.write('blat')
fp.close() fp.close()
@ -236,7 +236,7 @@ def _mkstemp_inner(dir, pre, suf, flags):
name = next(names) name = next(names)
file = _os.path.join(dir, pre + name + suf) file = _os.path.join(dir, pre + name + suf)
try: try:
fd = _os.open(file, flags, 0600) fd = _os.open(file, flags, 0o600)
_set_cloexec(fd) _set_cloexec(fd)
return (fd, _os.path.abspath(file)) return (fd, _os.path.abspath(file))
except OSError as e: except OSError as e:
@ -328,7 +328,7 @@ def mkdtemp(suffix="", prefix=template, dir=None):
name = next(names) name = next(names)
file = _os.path.join(dir, prefix + name + suffix) file = _os.path.join(dir, prefix + name + suffix)
try: try:
_os.mkdir(file, 0700) _os.mkdir(file, 0o700)
return file return file
except OSError as e: except OSError as e:
if e.errno == _errno.EEXIST: if e.errno == _errno.EEXIST:

View File

@ -4,39 +4,38 @@ BaseException
+-- Exception +-- Exception
+-- GeneratorExit +-- GeneratorExit
+-- StopIteration +-- StopIteration
+-- StandardError +-- ArithmeticError
| +-- ArithmeticError | +-- FloatingPointError
| | +-- FloatingPointError | +-- OverflowError
| | +-- OverflowError | +-- ZeroDivisionError
| | +-- ZeroDivisionError +-- AssertionError
| +-- AssertionError +-- AttributeError
| +-- AttributeError +-- EnvironmentError
| +-- EnvironmentError | +-- IOError
| | +-- IOError | +-- OSError
| | +-- OSError | +-- WindowsError (Windows)
| | +-- WindowsError (Windows) | +-- VMSError (VMS)
| | +-- VMSError (VMS) +-- EOFError
| +-- EOFError +-- ImportError
| +-- ImportError +-- LookupError
| +-- LookupError | +-- IndexError
| | +-- IndexError | +-- KeyError
| | +-- KeyError +-- MemoryError
| +-- MemoryError +-- NameError
| +-- NameError | +-- UnboundLocalError
| | +-- UnboundLocalError +-- ReferenceError
| +-- ReferenceError +-- RuntimeError
| +-- RuntimeError | +-- NotImplementedError
| | +-- NotImplementedError +-- SyntaxError
| +-- SyntaxError | +-- IndentationError
| | +-- IndentationError | +-- TabError
| | +-- TabError +-- SystemError
| +-- SystemError +-- TypeError
| +-- TypeError +-- ValueError
| +-- ValueError | +-- UnicodeError
| | +-- UnicodeError | +-- UnicodeDecodeError
| | +-- UnicodeDecodeError | +-- UnicodeEncodeError
| | +-- UnicodeEncodeError | +-- UnicodeTranslateError
| | +-- UnicodeTranslateError
+-- Warning +-- Warning
+-- DeprecationWarning +-- DeprecationWarning
+-- PendingDeprecationWarning +-- PendingDeprecationWarning

View File

@ -451,7 +451,7 @@ class CommonTest(seq_tests.CommonTest):
self.assertEqual(u, list("ham")) self.assertEqual(u, list("ham"))
def test_iadd(self): def test_iadd(self):
super(CommonTest, self).test_iadd() super().test_iadd()
u = self.type2test([0, 1]) u = self.type2test([0, 1])
u2 = u u2 = u
u += [2, 3] u += [2, 3]

View File

@ -46,8 +46,7 @@ __abs__: ()
__int__: () __int__: ()
__int__: () __int__: ()
__float__: () __float__: ()
__oct__: () __index__: ()
__hex__: ()
__hash__: () __hash__: ()
__repr__: () __repr__: ()
__str__: () __str__: ()

View File

@ -124,66 +124,80 @@ test_tokenize
39,5-39,7: OP '!=' 39,5-39,7: OP '!='
39,8-39,11: NUMBER '255' 39,8-39,11: NUMBER '255'
39,11-39,12: NEWLINE '\n' 39,11-39,12: NEWLINE '\n'
40,0-40,4: NUMBER '0377' 40,0-40,5: NUMBER '0o377'
40,5-40,7: OP '!=' 40,6-40,8: OP '!='
40,8-40,11: NUMBER '255' 40,9-40,12: NUMBER '255'
40,11-40,12: NEWLINE '\n' 40,12-40,13: NEWLINE '\n'
41,0-41,10: NUMBER '2147483647' 41,0-41,10: NUMBER '2147483647'
41,13-41,15: OP '!=' 41,13-41,15: OP '!='
41,16-41,28: NUMBER '017777777777' 41,16-41,29: NUMBER '0o17777777777'
41,28-41,29: NEWLINE '\n' 41,29-41,30: NEWLINE '\n'
42,0-42,1: OP '-' 42,0-42,1: OP '-'
42,1-42,11: NUMBER '2147483647' 42,1-42,11: NUMBER '2147483647'
42,11-42,12: OP '-' 42,11-42,12: OP '-'
42,12-42,13: NUMBER '1' 42,12-42,13: NUMBER '1'
42,14-42,16: OP '!=' 42,14-42,16: OP '!='
42,17-42,29: NUMBER '020000000000' 42,17-42,30: NUMBER '0o20000000000'
42,29-42,30: NEWLINE '\n' 42,30-42,31: NEWLINE '\n'
43,0-43,12: NUMBER '037777777777' 43,0-43,13: NUMBER '0o37777777777'
43,13-43,15: OP '!=' 43,14-43,16: OP '!='
43,16-43,17: OP '-' 43,17-43,18: OP '-'
43,17-43,18: NUMBER '1' 43,18-43,19: NUMBER '1'
43,18-43,19: NEWLINE '\n' 43,19-43,20: NEWLINE '\n'
44,0-44,10: NUMBER '0xffffffff' 44,0-44,10: NUMBER '0xffffffff'
44,11-44,13: OP '!=' 44,11-44,13: OP '!='
44,14-44,15: OP '-' 44,14-44,15: OP '-'
44,15-44,16: NUMBER '1' 44,15-44,16: NUMBER '1'
44,16-44,17: NEWLINE '\n' 44,16-44,17: OP ';'
44,18-44,31: NUMBER '0o37777777777'
44,32-44,34: OP '!='
44,35-44,36: OP '-'
44,36-44,37: NUMBER '1'
44,37-44,38: OP ';'
44,39-44,40: OP '-'
44,40-44,49: NUMBER '0o1234567'
44,50-44,52: OP '=='
44,53-44,64: NUMBER '0O001234567'
44,64-44,65: OP ';'
44,66-44,73: NUMBER '0b10101'
44,74-44,76: OP '=='
44,77-44,87: NUMBER '0B00010101'
44,87-44,88: NEWLINE '\n'
45,0-45,1: NL '\n' 45,0-45,1: NL '\n'
46,0-46,15: COMMENT '# Long integers' 46,0-46,15: COMMENT '# Long integers'
46,15-46,16: NL '\n' 46,15-46,16: NL '\n'
47,0-47,1: NAME 'x' 47,0-47,1: NAME 'x'
47,2-47,3: OP '=' 47,2-47,3: OP '='
47,4-47,6: NUMBER '0L' 47,4-47,5: NUMBER '0'
47,6-47,7: NEWLINE '\n' 47,5-47,6: NEWLINE '\n'
48,0-48,1: NAME 'x' 48,0-48,1: NAME 'x'
48,2-48,3: OP '=' 48,2-48,3: OP '='
48,4-48,6: NUMBER '0l' 48,4-48,5: NUMBER '0'
48,6-48,7: NEWLINE '\n' 48,5-48,6: NEWLINE '\n'
49,0-49,1: NAME 'x' 49,0-49,1: NAME 'x'
49,2-49,3: OP '=' 49,2-49,3: OP '='
49,4-49,23: NUMBER '0xffffffffffffffffL' 49,4-49,22: NUMBER '0xffffffffffffffff'
49,23-49,24: NEWLINE '\n' 49,22-49,23: NEWLINE '\n'
50,0-50,1: NAME 'x' 50,0-50,1: NAME 'x'
50,2-50,3: OP '=' 50,2-50,3: OP '='
50,4-50,23: NUMBER '0xffffffffffffffffl' 50,4-50,22: NUMBER '0xffffffffffffffff'
50,23-50,24: NEWLINE '\n' 50,22-50,23: NEWLINE '\n'
51,0-51,1: NAME 'x' 51,0-51,1: NAME 'x'
51,2-51,3: OP '=' 51,2-51,3: OP '='
51,4-51,23: NUMBER '077777777777777777L' 51,4-51,23: NUMBER '0o77777777777777777'
51,23-51,24: NEWLINE '\n' 51,23-51,24: NEWLINE '\n'
52,0-52,1: NAME 'x' 52,0-52,1: NAME 'x'
52,2-52,3: OP '=' 52,2-52,3: OP '='
52,4-52,23: NUMBER '077777777777777777l' 52,4-52,23: NUMBER '0B11101010111111111'
52,23-52,24: NEWLINE '\n' 52,23-52,24: NEWLINE '\n'
53,0-53,1: NAME 'x' 53,0-53,1: NAME 'x'
53,2-53,3: OP '=' 53,2-53,3: OP '='
53,4-53,35: NUMBER '123456789012345678901234567890L' 53,4-53,34: NUMBER '123456789012345678901234567890'
53,35-53,36: NEWLINE '\n' 53,34-53,35: NEWLINE '\n'
54,0-54,1: NAME 'x' 54,0-54,1: NAME 'x'
54,2-54,3: OP '=' 54,2-54,3: OP '='
54,4-54,35: NUMBER '123456789012345678901234567890l' 54,4-54,34: NUMBER '123456789012345678901234567890'
54,35-54,36: NEWLINE '\n' 54,34-54,35: NEWLINE '\n'
55,0-55,1: NL '\n' 55,0-55,1: NL '\n'
56,0-56,24: COMMENT '# Floating-point numbers' 56,0-56,24: COMMENT '# Floating-point numbers'
56,24-56,25: NL '\n' 56,24-56,25: NL '\n'

View File

@ -697,7 +697,7 @@ def dash_R_cleanup(fs, ps, pic):
import gc, copy_reg import gc, copy_reg
import _strptime, linecache, dircache import _strptime, linecache, dircache
import urlparse, urllib, urllib2, mimetypes, doctest import urlparse, urllib, urllib2, mimetypes, doctest
import struct, filecmp import struct, filecmp, collections
from distutils.dir_util import _path_created from distutils.dir_util import _path_created
# Restore some original values. # Restore some original values.
@ -707,6 +707,10 @@ def dash_R_cleanup(fs, ps, pic):
sys.path_importer_cache.clear() sys.path_importer_cache.clear()
sys.path_importer_cache.update(pic) sys.path_importer_cache.update(pic)
# Clear ABC registries.
for obj in [collections.Hashable, collections.Iterable]:
obj._ABCMeta__registry.clear()
# Clear assorted module caches. # Clear assorted module caches.
_path_created.clear() _path_created.clear()
re.purge() re.purge()

View File

@ -211,6 +211,32 @@ class BaseTest(unittest.TestCase):
self.checkraises(TypeError, 'hello', 'rindex') self.checkraises(TypeError, 'hello', 'rindex')
self.checkraises(TypeError, 'hello', 'rindex', 42) self.checkraises(TypeError, 'hello', 'rindex', 42)
def test_lower(self):
self.checkequal('hello', 'HeLLo', 'lower')
self.checkequal('hello', 'hello', 'lower')
self.checkraises(TypeError, 'hello', 'lower', 42)
def test_upper(self):
self.checkequal('HELLO', 'HeLLo', 'upper')
self.checkequal('HELLO', 'HELLO', 'upper')
self.checkraises(TypeError, 'hello', 'upper', 42)
def test_expandtabs(self):
self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
# This test is only valid when sizeof(int) == sizeof(void*) == 4.
if sys.maxint < (1 << 32) and struct.calcsize('P') == 4:
self.checkraises(OverflowError,
'\ta\n\tb', 'expandtabs', sys.maxint)
def test_split(self): def test_split(self):
# by a char # by a char
self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|') self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')

123
Lib/test/test_abc.py Normal file
View File

@ -0,0 +1,123 @@
# Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Unit tests for abc.py."""
import sys
import unittest
from test import test_support
import abc
class TestABC(unittest.TestCase):
def test_abstractmethod_basics(self):
@abc.abstractmethod
def foo(self): pass
self.assertEqual(foo.__isabstractmethod__, True)
def bar(self): pass
self.assertEqual(hasattr(bar, "__isabstractmethod__"), False)
def test_abstractmethod_integration(self):
class C(metaclass=abc.ABCMeta):
@abc.abstractmethod
def foo(self): pass # abstract
def bar(self): pass # concrete
self.assertEqual(C.__abstractmethods__, {"foo"})
self.assertRaises(TypeError, C) # because foo is abstract
class D(C):
def bar(self): pass # concrete override of concrete
self.assertEqual(D.__abstractmethods__, {"foo"})
self.assertRaises(TypeError, D) # because foo is still abstract
class E(D):
def foo(self): pass
self.assertEqual(E.__abstractmethods__, set())
E() # now foo is concrete, too
class F(E):
@abc.abstractmethod
def bar(self): pass # abstract override of concrete
self.assertEqual(F.__abstractmethods__, {"bar"})
self.assertRaises(TypeError, F) # because bar is abstract now
def test_registration_basics(self):
class A(metaclass=abc.ABCMeta):
pass
class B:
pass
b = B()
self.assertEqual(issubclass(B, A), False)
self.assertEqual(isinstance(b, A), False)
A.register(B)
self.assertEqual(issubclass(B, A), True)
self.assertEqual(isinstance(b, A), True)
class C(B):
pass
c = C()
self.assertEqual(issubclass(C, A), True)
self.assertEqual(isinstance(c, A), True)
def test_registration_builtins(self):
class A(metaclass=abc.ABCMeta):
pass
A.register(int)
self.assertEqual(isinstance(42, A), True)
self.assertEqual(issubclass(int, A), True)
class B(A):
pass
B.register(basestring)
self.assertEqual(isinstance("", A), True)
self.assertEqual(issubclass(str, A), True)
def test_registration_edge_cases(self):
class A(metaclass=abc.ABCMeta):
pass
A.register(A) # should pass silently
class A1(A):
pass
self.assertRaises(RuntimeError, A1.register, A) # cycles not allowed
class B:
pass
A1.register(B) # ok
A1.register(B) # should pass silently
class C(A):
pass
A.register(C) # should pass silently
self.assertRaises(RuntimeError, C.register, A) # cycles not allowed
C.register(B) # ok
def test_registration_transitiveness(self):
class A(metaclass=abc.ABCMeta):
pass
self.failUnless(issubclass(A, A))
class B(metaclass=abc.ABCMeta):
pass
self.failIf(issubclass(A, B))
self.failIf(issubclass(B, A))
class C(metaclass=abc.ABCMeta):
pass
A.register(B)
class B1(B):
pass
self.failUnless(issubclass(B1, A))
class C1(C):
pass
B1.register(C1)
self.failIf(issubclass(C, B))
self.failIf(issubclass(C, B1))
self.failUnless(issubclass(C1, A))
self.failUnless(issubclass(C1, B))
self.failUnless(issubclass(C1, B1))
C1.register(int)
class MyInt(int):
pass
self.failUnless(issubclass(MyInt, A))
self.failUnless(isinstance(42, A))
def test_main():
test_support.run_unittest(TestABC)
if __name__ == "__main__":
unittest.main()

View File

@ -704,7 +704,7 @@ class BaseTest(unittest.TestCase):
class StringTest(BaseTest): class StringTest(BaseTest):
def test_setitem(self): def test_setitem(self):
super(StringTest, self).test_setitem() super().test_setitem()
a = array.array(self.typecode, self.example) a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2]) self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2])

View File

@ -728,8 +728,27 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, int, 1, 12) self.assertRaises(TypeError, int, 1, 12)
self.assertEqual(int('0123', 0), 83) # tests with base 0
self.assertRaises(ValueError, int, ' 0123 ', 0) # old octal syntax
self.assertEqual(int('000', 0), 0)
self.assertEqual(int('0o123', 0), 83)
self.assertEqual(int('0x123', 0), 291)
self.assertEqual(int('0b100', 0), 4)
self.assertEqual(int(' 0O123 ', 0), 83)
self.assertEqual(int(' 0X123 ', 0), 291)
self.assertEqual(int(' 0B100 ', 0), 4)
# without base still base 10
self.assertEqual(int('0123'), 123)
self.assertEqual(int('0123', 10), 123)
# tests with prefix and base != 0
self.assertEqual(int('0x123', 16), 291) self.assertEqual(int('0x123', 16), 291)
self.assertEqual(int('0o123', 8), 83)
self.assertEqual(int('0b100', 2), 4)
self.assertEqual(int('0X123', 16), 291)
self.assertEqual(int('0O123', 8), 83)
self.assertEqual(int('0B100', 2), 4)
# SF bug 1334662: int(string, base) wrong answers # SF bug 1334662: int(string, base) wrong answers
# Various representations of 2**32 evaluated to 0 # Various representations of 2**32 evaluated to 0
@ -1269,10 +1288,10 @@ class BuiltinTest(unittest.TestCase):
self.assertEquals(next(it, 42), 42) self.assertEquals(next(it, 42), 42)
def test_oct(self): def test_oct(self):
self.assertEqual(oct(100), '0144') self.assertEqual(oct(100), '0o144')
self.assertEqual(oct(100), '0144') self.assertEqual(oct(100), '0o144')
self.assertEqual(oct(-100), '-0144') self.assertEqual(oct(-100), '-0o144')
self.assertEqual(oct(-100), '-0144') self.assertEqual(oct(-100), '-0o144')
self.assertRaises(TypeError, oct, ()) self.assertRaises(TypeError, oct, ())
def write_testfile(self): def write_testfile(self):

View File

@ -716,6 +716,12 @@ class BytesAsStringTest(test.string_tests.BaseTest):
pass pass
def test_find(self): def test_find(self):
pass pass
def test_expandtabs(self):
pass
def test_upper(self):
pass
def test_lower(self):
pass
def test_main(): def test_main():

View File

@ -50,7 +50,7 @@ def do_test(buf, method):
raise ValueError, "unknown method: %s" % method raise ValueError, "unknown method: %s" % method
try: try:
return cgi.parse(fp, env, strict_parsing=1) return cgi.parse(fp, env, strict_parsing=1)
except StandardError as err: except Exception as err:
return ComparableException(err) return ComparableException(err)
# A list of test cases. Each test case is a a two-tuple that contains # A list of test cases. Each test case is a a two-tuple that contains

View File

@ -80,18 +80,14 @@ class AllTests:
print("__int__:", args) print("__int__:", args)
return 1 return 1
def __index__(self, *args):
print("__index__:", args)
return 1
def __float__(self, *args): def __float__(self, *args):
print("__float__:", args) print("__float__:", args)
return 1.0 return 1.0
def __oct__(self, *args):
print("__oct__:", args)
return '01'
def __hex__(self, *args):
print("__hex__:", args)
return '0x1'
def __cmp__(self, *args): def __cmp__(self, *args):
print("__cmp__:", args) print("__cmp__:", args)
return 0 return 0
@ -237,7 +233,6 @@ int(testme)
int(testme) int(testme)
float(testme) float(testme)
oct(testme) oct(testme)
hex(testme)
# And the rest... # And the rest...
@ -287,8 +282,6 @@ class BadTypeClass:
__float__ = __int__ __float__ = __int__
__str__ = __int__ __str__ = __int__
__repr__ = __int__ __repr__ = __int__
__oct__ = __int__
__hex__ = __int__
def check_exc(stmt, exception): def check_exc(stmt, exception):
"""Raise TestFailed if executing 'stmt' does not raise 'exception' """Raise TestFailed if executing 'stmt' does not raise 'exception'

View File

@ -1,6 +1,14 @@
"""Unit tests for collections.py."""
import unittest import unittest
from test import test_support from test import test_support
from collections import NamedTuple from collections import NamedTuple
from collections import Hashable, Iterable, Iterator
from collections import Sized, Container, Callable
from collections import Set, MutableSet
from collections import Mapping, MutableMapping
from collections import Sequence, MutableSequence
class TestNamedTuple(unittest.TestCase): class TestNamedTuple(unittest.TestCase):
@ -51,11 +59,187 @@ class TestNamedTuple(unittest.TestCase):
self.assertRaises(AttributeError, eval, 'p.z', locals()) self.assertRaises(AttributeError, eval, 'p.z', locals())
class TestOneTrickPonyABCs(unittest.TestCase):
def test_Hashable(self):
# Check some non-hashables
non_samples = [bytes(), list(), set(), dict()]
for x in non_samples:
self.failIf(isinstance(x, Hashable), repr(x))
self.failIf(issubclass(type(x), Hashable), repr(type(x)))
# Check some hashables
samples = [None,
int(), float(), complex(),
str(), unicode(),
tuple(), frozenset(),
int, list, object, type,
]
for x in samples:
self.failUnless(isinstance(x, Hashable), repr(x))
self.failUnless(issubclass(type(x), Hashable), repr(type(x)))
self.assertRaises(TypeError, Hashable)
# Check direct subclassing
class H(Hashable):
def __hash__(self):
return super().__hash__()
self.assertEqual(hash(H()), 0)
self.failIf(issubclass(int, H))
def test_Iterable(self):
# Check some non-iterables
non_samples = [None, 42, 3.14, 1j]
for x in non_samples:
self.failIf(isinstance(x, Iterable), repr(x))
self.failIf(issubclass(type(x), Iterable), repr(type(x)))
# Check some iterables
samples = [bytes(), str(), unicode(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
(lambda: (yield))(),
(x for x in []),
]
for x in samples:
self.failUnless(isinstance(x, Iterable), repr(x))
self.failUnless(issubclass(type(x), Iterable), repr(type(x)))
# Check direct subclassing
class I(Iterable):
def __iter__(self):
return super().__iter__()
self.assertEqual(list(I()), [])
self.failIf(issubclass(str, I))
def test_Iterator(self):
non_samples = [None, 42, 3.14, 1j, b"", "", u"", (), [], {}, set()]
for x in non_samples:
self.failIf(isinstance(x, Iterator), repr(x))
self.failIf(issubclass(type(x), Iterator), repr(type(x)))
samples = [iter(bytes()), iter(str()), iter(unicode()),
iter(tuple()), iter(list()), iter(dict()),
iter(set()), iter(frozenset()),
iter(dict().keys()), iter(dict().items()),
iter(dict().values()),
(lambda: (yield))(),
(x for x in []),
]
for x in samples:
self.failUnless(isinstance(x, Iterator), repr(x))
self.failUnless(issubclass(type(x), Iterator), repr(type(x)))
def test_Sized(self):
non_samples = [None, 42, 3.14, 1j,
(lambda: (yield))(),
(x for x in []),
]
for x in non_samples:
self.failIf(isinstance(x, Sized), repr(x))
self.failIf(issubclass(type(x), Sized), repr(type(x)))
samples = [bytes(), str(), unicode(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
]
for x in samples:
self.failUnless(isinstance(x, Sized), repr(x))
self.failUnless(issubclass(type(x), Sized), repr(type(x)))
def test_Container(self):
non_samples = [None, 42, 3.14, 1j,
(lambda: (yield))(),
(x for x in []),
]
for x in non_samples:
self.failIf(isinstance(x, Container), repr(x))
self.failIf(issubclass(type(x), Container), repr(type(x)))
samples = [bytes(), str(), unicode(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(),
]
for x in samples:
self.failUnless(isinstance(x, Container), repr(x))
self.failUnless(issubclass(type(x), Container), repr(type(x)))
def test_Callable(self):
non_samples = [None, 42, 3.14, 1j,
"", b"", (), [], {}, set(),
(lambda: (yield))(),
(x for x in []),
]
for x in non_samples:
self.failIf(isinstance(x, Callable), repr(x))
self.failIf(issubclass(type(x), Callable), repr(type(x)))
samples = [lambda: None,
type, int, object,
len,
list.append, [].append,
]
for x in samples:
self.failUnless(isinstance(x, Callable), repr(x))
self.failUnless(issubclass(type(x), Callable), repr(type(x)))
def test_direct_subclassing(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C(B):
pass
self.failUnless(issubclass(C, B))
self.failIf(issubclass(int, C))
def test_registration(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C:
__hash__ = None # Make sure it isn't hashable by default
self.failIf(issubclass(C, B), B.__name__)
B.register(C)
self.failUnless(issubclass(C, B))
class TestCollectionABCs(unittest.TestCase):
# XXX For now, we only test some virtual inheritance properties.
# We should also test the proper behavior of the collection ABCs
# as real base classes or mix-in classes.
def test_Set(self):
for sample in [set, frozenset]:
self.failUnless(isinstance(sample(), Set))
self.failUnless(issubclass(sample, Set))
def test_MutableSet(self):
self.failUnless(isinstance(set(), MutableSet))
self.failUnless(issubclass(set, MutableSet))
self.failIf(isinstance(frozenset(), MutableSet))
self.failIf(issubclass(frozenset, MutableSet))
def test_Mapping(self):
for sample in [dict]:
self.failUnless(isinstance(sample(), Mapping))
self.failUnless(issubclass(sample, Mapping))
def test_MutableMapping(self):
for sample in [dict]:
self.failUnless(isinstance(sample(), MutableMapping))
self.failUnless(issubclass(sample, MutableMapping))
def test_Sequence(self):
for sample in [tuple, list, bytes, str]:
self.failUnless(isinstance(sample(), Sequence))
self.failUnless(issubclass(sample, Sequence))
self.failUnless(issubclass(basestring, Sequence))
def test_MutableSequence(self):
for sample in [tuple, str]:
self.failIf(isinstance(sample(), MutableSequence))
self.failIf(issubclass(sample, MutableSequence))
for sample in [list, bytes]:
self.failUnless(isinstance(sample(), MutableSequence))
self.failUnless(issubclass(sample, MutableSequence))
self.failIf(issubclass(basestring, MutableSequence))
def test_main(verbose=None): def test_main(verbose=None):
import collections as CollectionsModule import collections as CollectionsModule
test_classes = [TestNamedTuple] test_classes = [TestNamedTuple, TestOneTrickPonyABCs, TestCollectionABCs]
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
test_support.run_doctest(CollectionsModule, verbose) test_support.run_doctest(CollectionsModule, verbose)
if __name__ == "__main__": if __name__ == "__main__":
test_main(verbose=True) test_main(verbose=True)

View File

@ -36,6 +36,9 @@ class TestSpecifics(unittest.TestCase):
def test_syntax_error(self): def test_syntax_error(self):
self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec") self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
def test_none_keyword_arg(self):
self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
def test_duplicate_global_local(self): def test_duplicate_global_local(self):
try: try:
exec('def f(a): global a; a = 1') exec('def f(a): global a; a = 1')
@ -158,21 +161,22 @@ if 1:
def test_literals_with_leading_zeroes(self): def test_literals_with_leading_zeroes(self):
for arg in ["077787", "0xj", "0x.", "0e", "090000000000000", for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
"080000000000000", "000000000000009", "000000000000008"]: "080000000000000", "000000000000009", "000000000000008",
"0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
"0b101j2", "0o153j2", "0b100e1", "0o777e1", "0777",
"000777", "000000000000007"]:
self.assertRaises(SyntaxError, eval, arg) self.assertRaises(SyntaxError, eval, arg)
self.assertEqual(eval("0777"), 511)
self.assertEqual(eval("000777"), 511)
self.assertEqual(eval("0xff"), 255) self.assertEqual(eval("0xff"), 255)
self.assertEqual(eval("0XfF"), 255)
self.assertEqual(eval("0777."), 777) self.assertEqual(eval("0777."), 777)
self.assertEqual(eval("0777.0"), 777) self.assertEqual(eval("0777.0"), 777)
self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777) self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
self.assertEqual(eval("0777e1"), 7770) self.assertEqual(eval("0777e1"), 7770)
self.assertEqual(eval("0e0"), 0) self.assertEqual(eval("0e0"), 0)
self.assertEqual(eval("0000E-012"), 0) self.assertEqual(eval("0000e-012"), 0)
self.assertEqual(eval("09.5"), 9.5) self.assertEqual(eval("09.5"), 9.5)
self.assertEqual(eval("0777j"), 777j) self.assertEqual(eval("0777j"), 777j)
self.assertEqual(eval("000"), 0)
self.assertEqual(eval("00j"), 0j) self.assertEqual(eval("00j"), 0j)
self.assertEqual(eval("00.0"), 0) self.assertEqual(eval("00.0"), 0)
self.assertEqual(eval("0e3"), 0) self.assertEqual(eval("0e3"), 0)
@ -181,9 +185,12 @@ if 1:
self.assertEqual(eval("090000000000000e0"), 90000000000000.) self.assertEqual(eval("090000000000000e0"), 90000000000000.)
self.assertEqual(eval("090000000000000e-0"), 90000000000000.) self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
self.assertEqual(eval("090000000000000j"), 90000000000000j) self.assertEqual(eval("090000000000000j"), 90000000000000j)
self.assertEqual(eval("000000000000007"), 7)
self.assertEqual(eval("000000000000008."), 8.) self.assertEqual(eval("000000000000008."), 8.)
self.assertEqual(eval("000000000000009."), 9.) self.assertEqual(eval("000000000000009."), 9.)
self.assertEqual(eval("0b101010"), 42)
self.assertEqual(eval("-0b000000000010"), -2)
self.assertEqual(eval("0o777"), 511)
self.assertEqual(eval("-0o0000010"), -8)
def test_unary_minus(self): def test_unary_minus(self):
# Verify treatment of unary minus on negative numbers SF bug #660455 # Verify treatment of unary minus on negative numbers SF bug #660455

View File

@ -2126,17 +2126,14 @@ def inherits():
class octlong(int): class octlong(int):
__slots__ = [] __slots__ = []
def __str__(self): def __str__(self):
s = oct(self) return oct(self)
if s[-1] == 'L':
s = s[:-1]
return s
def __add__(self, other): def __add__(self, other):
return self.__class__(super(octlong, self).__add__(other)) return self.__class__(super(octlong, self).__add__(other))
__radd__ = __add__ __radd__ = __add__
vereq(str(octlong(3) + 5), "010") vereq(str(octlong(3) + 5), "0o10")
# (Note that overriding __radd__ here only seems to work # (Note that overriding __radd__ here only seems to work
# because the example uses a short int left argument.) # because the example uses a short int left argument.)
vereq(str(5 + octlong(3000)), "05675") vereq(str(5 + octlong(3000)), "0o5675")
a = octlong(12345) a = octlong(12345)
vereq(a, 12345) vereq(a, 12345)
vereq(int(a), 12345) vereq(int(a), 12345)

View File

@ -45,17 +45,17 @@ class DumbDBMTestCase(unittest.TestCase):
return return
try: try:
old_umask = os.umask(0002) old_umask = os.umask(0o002)
f = dumbdbm.open(_fname, 'c', 0637) f = dumbdbm.open(_fname, 'c', 0o637)
f.close() f.close()
finally: finally:
os.umask(old_umask) os.umask(old_umask)
expected_mode = 0635 expected_mode = 0o635
if os.name != 'posix': if os.name != 'posix':
# Windows only supports setting the read-only attribute. # Windows only supports setting the read-only attribute.
# This shouldn't fail, but doesn't work like Unix either. # This shouldn't fail, but doesn't work like Unix either.
expected_mode = 0666 expected_mode = 0o666
import stat import stat
st = os.stat(_fname + '.dat') st = os.stat(_fname + '.dat')

View File

@ -121,7 +121,7 @@ testboth("%#+027.23X", big, "+0X0001234567890ABCDEF12345")
# same, except no 0 flag # same, except no 0 flag
testboth("%#+27.23X", big, " +0X001234567890ABCDEF12345") testboth("%#+27.23X", big, " +0X001234567890ABCDEF12345")
big = 012345670123456701234567012345670 # 32 octal digits big = 0o12345670123456701234567012345670 # 32 octal digits
testboth("%o", big, "12345670123456701234567012345670") testboth("%o", big, "12345670123456701234567012345670")
testboth("%o", -big, "-12345670123456701234567012345670") testboth("%o", -big, "-12345670123456701234567012345670")
testboth("%5o", -big, "-12345670123456701234567012345670") testboth("%5o", -big, "-12345670123456701234567012345670")
@ -141,33 +141,36 @@ testboth("%.33o", big, "012345670123456701234567012345670")
testboth("%34.33o", big, " 012345670123456701234567012345670") testboth("%34.33o", big, " 012345670123456701234567012345670")
testboth("%-34.33o", big, "012345670123456701234567012345670 ") testboth("%-34.33o", big, "012345670123456701234567012345670 ")
testboth("%o", big, "12345670123456701234567012345670") testboth("%o", big, "12345670123456701234567012345670")
testboth("%#o", big, "012345670123456701234567012345670") testboth("%#o", big, "0o12345670123456701234567012345670")
testboth("%#o", -big, "-012345670123456701234567012345670") testboth("%#o", -big, "-0o12345670123456701234567012345670")
testboth("%#.34o", -big, "-0012345670123456701234567012345670") testboth("%#.34o", -big, "-0o0012345670123456701234567012345670")
testboth("%#+.34o", big, "+0012345670123456701234567012345670") testboth("%#+.34o", big, "+0o0012345670123456701234567012345670")
testboth("%# .34o", big, " 0012345670123456701234567012345670") testboth("%# .34o", big, " 0o0012345670123456701234567012345670")
testboth("%#+.34o", big, "+0012345670123456701234567012345670") testboth("%#-+.34o", big, "+0o0012345670123456701234567012345670")
testboth("%#-+.34o", big, "+0012345670123456701234567012345670") testboth("%#-+39.34o", big, "+0o0012345670123456701234567012345670 ")
testboth("%#-+37.34o", big, "+0012345670123456701234567012345670 ") testboth("%#+39.34o", big, " +0o0012345670123456701234567012345670")
testboth("%#+37.34o", big, " +0012345670123456701234567012345670")
# next one gets one leading zero from precision # next one gets one leading zero from precision
testboth("%.33o", big, "012345670123456701234567012345670") testboth("%.33o", big, "012345670123456701234567012345670")
# base marker shouldn't change that, since "0" is redundant # one leading zero from precision
testboth("%#.33o", big, "012345670123456701234567012345670") testboth("%#.33o", big, "0o012345670123456701234567012345670")
# but reduce precision, and base marker should add a zero # leading zero vanishes
testboth("%#.32o", big, "012345670123456701234567012345670") testboth("%#.32o", big, "0o12345670123456701234567012345670")
# one leading zero from precision, and another from "0" flag & width # one leading zero from precision, and another from '0' flag & width
testboth("%034.33o", big, "0012345670123456701234567012345670") testboth("%034.33o", big, "0012345670123456701234567012345670")
# base marker shouldn't change that # max width includes base marker; padding zeroes come after marker
testboth("%0#34.33o", big, "0012345670123456701234567012345670") testboth("%0#38.33o", big, "0o000012345670123456701234567012345670")
# padding spaces come before marker
testboth("%#36.33o", big, " 0o012345670123456701234567012345670")
# Some small ints, in both Python int and long flavors). # Some small ints, in both Python int and long flavors).
testboth("%d", 42, "42") testboth("%d", 42, "42")
testboth("%d", -42, "-42") testboth("%d", -42, "-42")
testboth("%#x", 1, "0x1") testboth("%#x", 1, "0x1")
testboth("%#X", 1, "0X1") testboth("%#X", 1, "0X1")
testboth("%#o", 1, "01") testboth("%#o", 1, "0o1")
testboth("%#o", 0, "0") testboth("%#o", 1, "0o1")
testboth("%#o", 0, "0o0")
testboth("%#o", 0, "0o0")
testboth("%o", 0, "0") testboth("%o", 0, "0")
testboth("%d", 0, "0") testboth("%d", 0, "0")
testboth("%#x", 0, "0x0") testboth("%#x", 0, "0x0")
@ -176,8 +179,10 @@ testboth("%#X", 0, "0X0")
testboth("%x", 0x42, "42") testboth("%x", 0x42, "42")
testboth("%x", -0x42, "-42") testboth("%x", -0x42, "-42")
testboth("%o", 042, "42") testboth("%o", 0o42, "42")
testboth("%o", -042, "-42") testboth("%o", -0o42, "-42")
testboth("%o", 0o42, "42")
testboth("%o", -0o42, "-42")
# Test exception for unknown format characters # Test exception for unknown format characters
if verbose: if verbose:
@ -216,14 +221,6 @@ test_exc('no format', '1', TypeError,
test_exc('no format', '1', TypeError, test_exc('no format', '1', TypeError,
"not all arguments converted during string formatting") "not all arguments converted during string formatting")
class Foobar(int):
def __oct__(self):
# Returning a non-string should not blow up.
return self + 1
test_exc('%o', Foobar(), TypeError,
"expected string, int found")
if maxsize == 2**31-1: if maxsize == 2**31-1:
# crashes 2.2.1 and earlier: # crashes 2.2.1 and earlier:
try: try:

View File

@ -27,26 +27,32 @@ class TokenTests(unittest.TestCase):
self.assertEquals(x, 0, 'backslash ending comment') self.assertEquals(x, 0, 'backslash ending comment')
def testPlainIntegers(self): def testPlainIntegers(self):
self.assertEquals(type(000), type(0))
self.assertEquals(0xff, 255) self.assertEquals(0xff, 255)
self.assertEquals(0377, 255) self.assertEquals(0o377, 255)
self.assertEquals(2147483647, 017777777777) self.assertEquals(2147483647, 0o17777777777)
self.assertEquals(0b1001, 9)
from sys import maxint from sys import maxint
if maxint == 2147483647: if maxint == 2147483647:
self.assertEquals(-2147483647-1, -020000000000) self.assertEquals(-2147483647-1, -0o20000000000)
# XXX -2147483648 # XXX -2147483648
self.assert_(037777777777 > 0) self.assert_(0o37777777777 > 0)
self.assert_(0xffffffff > 0) self.assert_(0xffffffff > 0)
for s in '2147483648', '040000000000', '0x100000000': self.assert_(0b1111111111111111111111111111111 > 0)
for s in ('2147483648', '0o40000000000', '0x100000000',
'0b10000000000000000000000000000000'):
try: try:
x = eval(s) x = eval(s)
except OverflowError: except OverflowError:
self.fail("OverflowError on huge integer literal %r" % s) self.fail("OverflowError on huge integer literal %r" % s)
elif maxint == 9223372036854775807: elif maxint == 9223372036854775807:
self.assertEquals(-9223372036854775807-1, -01000000000000000000000) self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
self.assert_(01777777777777777777777 > 0) self.assert_(0o1777777777777777777777 > 0)
self.assert_(0xffffffffffffffff > 0) self.assert_(0xffffffffffffffff > 0)
for s in '9223372036854775808', '02000000000000000000000', \ self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
'0x10000000000000000': for s in '9223372036854775808', '0o2000000000000000000000', \
'0x10000000000000000', \
'0b100000000000000000000000000000000000000000000000000000000000000':
try: try:
x = eval(s) x = eval(s)
except OverflowError: except OverflowError:
@ -55,14 +61,14 @@ class TokenTests(unittest.TestCase):
self.fail('Weird maxint value %r' % maxint) self.fail('Weird maxint value %r' % maxint)
def testLongIntegers(self): def testLongIntegers(self):
x = 0
x = 0 x = 0
x = 0xffffffffffffffff x = 0xffffffffffffffff
x = 0xffffffffffffffff x = 0Xffffffffffffffff
x = 077777777777777777 x = 0o77777777777777777
x = 077777777777777777 x = 0O77777777777777777
x = 123456789012345678901234567890
x = 123456789012345678901234567890 x = 123456789012345678901234567890
x = 0b100000000000000000000000000000000000000000000000000000000000000000000
x = 0B111111111111111111111111111111111111111111111111111111111111111111111
def testFloats(self): def testFloats(self):
x = 3.14 x = 3.14

View File

@ -65,49 +65,49 @@ class TextHexOct(unittest.TestCase):
def test_oct_baseline(self): def test_oct_baseline(self):
# Baseline tests # Baseline tests
self.assertEqual(00, 0) self.assertEqual(00, 0)
self.assertEqual(020, 16) self.assertEqual(0o20, 16)
if platform_long_is_32_bits: if platform_long_is_32_bits:
self.assertEqual(017777777777, 2147483647) self.assertEqual(0o17777777777, 2147483647)
else: else:
self.assertEqual(0777777777777777777777, 9223372036854775807) self.assertEqual(0o777777777777777777777, 9223372036854775807)
# Ditto with a minus sign and parentheses # Ditto with a minus sign and parentheses
self.assertEqual(-(00), 0) self.assertEqual(-(00), 0)
self.assertEqual(-(020), -16) self.assertEqual(-(0o20), -16)
if platform_long_is_32_bits: if platform_long_is_32_bits:
self.assertEqual(-(017777777777), -2147483647) self.assertEqual(-(0o17777777777), -2147483647)
else: else:
self.assertEqual(-(0777777777777777777777), -9223372036854775807) self.assertEqual(-(0o777777777777777777777), -9223372036854775807)
# Ditto with a minus sign and NO parentheses # Ditto with a minus sign and NO parentheses
self.assertEqual(-00, 0) self.assertEqual(-00, 0)
self.assertEqual(-020, -16) self.assertEqual(-0o20, -16)
if platform_long_is_32_bits: if platform_long_is_32_bits:
self.assertEqual(-017777777777, -2147483647) self.assertEqual(-0o17777777777, -2147483647)
else: else:
self.assertEqual(-0777777777777777777777, -9223372036854775807) self.assertEqual(-0o777777777777777777777, -9223372036854775807)
def test_oct_unsigned(self): def test_oct_unsigned(self):
if platform_long_is_32_bits: if platform_long_is_32_bits:
# Positive constants # Positive constants
self.assertEqual(020000000000, 2147483648) self.assertEqual(0o20000000000, 2147483648)
self.assertEqual(037777777777, 4294967295) self.assertEqual(0o37777777777, 4294967295)
# Ditto with a minus sign and parentheses # Ditto with a minus sign and parentheses
self.assertEqual(-(020000000000), -2147483648) self.assertEqual(-(0o20000000000), -2147483648)
self.assertEqual(-(037777777777), -4294967295) self.assertEqual(-(0o37777777777), -4294967295)
# Ditto with a minus sign and NO parentheses # Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1 # This failed in Python 2.2 through 2.2.2 and in 2.3a1
self.assertEqual(-020000000000, -2147483648) self.assertEqual(-0o20000000000, -2147483648)
self.assertEqual(-037777777777, -4294967295) self.assertEqual(-0o37777777777, -4294967295)
else: else:
# Positive constants # Positive constants
self.assertEqual(01000000000000000000000, 9223372036854775808) self.assertEqual(0o1000000000000000000000, 9223372036854775808)
self.assertEqual(01777777777777777777777, 18446744073709551615) self.assertEqual(0o1777777777777777777777, 18446744073709551615)
# Ditto with a minus sign and parentheses # Ditto with a minus sign and parentheses
self.assertEqual(-(01000000000000000000000), -9223372036854775808) self.assertEqual(-(0o1000000000000000000000), -9223372036854775808)
self.assertEqual(-(01777777777777777777777), -18446744073709551615) self.assertEqual(-(0o1777777777777777777777), -18446744073709551615)
# Ditto with a minus sign and NO parentheses # Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1 # This failed in Python 2.2 through 2.2.2 and in 2.3a1
self.assertEqual(-01000000000000000000000, -9223372036854775808) self.assertEqual(-0o1000000000000000000000, -9223372036854775808)
self.assertEqual(-01777777777777777777777, -18446744073709551615) self.assertEqual(-0o1777777777777777777777, -18446744073709551615)
def test_main(): def test_main():
test_support.run_unittest(TextHexOct) test_support.run_unittest(TextHexOct)

View File

@ -5,7 +5,7 @@ class ListTest(list_tests.CommonTest):
type2test = list type2test = list
def test_truth(self): def test_truth(self):
super(ListTest, self).test_truth() super().test_truth()
self.assert_(not []) self.assert_(not [])
self.assert_([42]) self.assert_([42])
@ -13,7 +13,7 @@ class ListTest(list_tests.CommonTest):
self.assert_([] is not []) self.assert_([] is not [])
def test_len(self): def test_len(self):
super(ListTest, self).test_len() super().test_len()
self.assertEqual(len([]), 0) self.assertEqual(len([]), 0)
self.assertEqual(len([0]), 1) self.assertEqual(len([0]), 1)
self.assertEqual(len([0, 1, 2]), 3) self.assertEqual(len([0, 1, 2]), 3)

View File

@ -195,9 +195,6 @@ class LongTest(unittest.TestCase):
self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2)) self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
def slow_format(self, x, base): def slow_format(self, x, base):
if (x, base) == (0, 8):
# this is an oddball!
return "0"
digits = [] digits = []
sign = 0 sign = 0
if x < 0: if x < 0:
@ -208,7 +205,7 @@ class LongTest(unittest.TestCase):
digits.reverse() digits.reverse()
digits = digits or [0] digits = digits or [0]
return '-'[:sign] + \ return '-'[:sign] + \
{8: '0', 10: '', 16: '0x'}[base] + \ {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
"".join(map(lambda i: "0123456789abcdef"[i], digits)) "".join(map(lambda i: "0123456789abcdef"[i], digits))
def check_format_1(self, x): def check_format_1(self, x):

View File

@ -136,6 +136,16 @@ class Test_IncrementalDecoder(unittest.TestCase):
self.assertRaises(UnicodeDecodeError, decoder.decode, '', True) self.assertRaises(UnicodeDecodeError, decoder.decode, '', True)
self.assertEqual(decoder.decode('B@$'), '\u4e16') self.assertEqual(decoder.decode('B@$'), '\u4e16')
class Test_StreamReader(unittest.TestCase):
def test_bug1728403(self):
try:
open(TESTFN, 'w').write('\xa1')
f = codecs.open(TESTFN, encoding='cp949')
self.assertRaises(UnicodeDecodeError, f.read, 2)
finally:
try: f.close()
except: pass
os.unlink(TESTFN)
class Test_StreamWriter(unittest.TestCase): class Test_StreamWriter(unittest.TestCase):
if len('\U00012345') == 2: # UCS2 if len('\U00012345') == 2: # UCS2

View File

@ -39,16 +39,24 @@ class TestTranforms(unittest.TestCase):
asm = dis_single(line) asm = dis_single(line)
self.assert_(elem in asm) self.assert_(elem in asm)
def test_none_as_constant(self): def test_global_as_constant(self):
# LOAD_GLOBAL None --> LOAD_CONST None # LOAD_GLOBAL None/True/False --> LOAD_CONST None/True/False
def f(x): def f(x):
None
None None
return x return x
asm = disassemble(f) def g(x):
for elem in ('LOAD_GLOBAL',): True
self.assert_(elem not in asm) return x
for elem in ('LOAD_CONST', '(None)'): def h(x):
self.assert_(elem in asm) False
return x
for func, name in ((f, 'None'), (g, 'True'), (h, 'False')):
asm = disassemble(func)
for elem in ('LOAD_GLOBAL',):
self.assert_(elem not in asm)
for elem in ('LOAD_CONST', '('+name+')'):
self.assert_(elem in asm)
def f(): def f():
'Adding a docstring made this test fail in Py2.5.0' 'Adding a docstring made this test fail in Py2.5.0'
return None return None

View File

@ -131,22 +131,22 @@ class UsageTests(unittest.TestCase):
"""Catching 'object_' should raise a TypeError.""" """Catching 'object_' should raise a TypeError."""
try: try:
try: try:
raise StandardError raise Exception
except object_: except object_:
pass pass
except TypeError: except TypeError:
pass pass
except StandardError: except Exception:
self.fail("TypeError expected when catching %s" % type(object_)) self.fail("TypeError expected when catching %s" % type(object_))
try: try:
try: try:
raise StandardError raise Exception
except (object_,): except (object_,):
pass pass
except TypeError: except TypeError:
return return
except StandardError: except Exception:
self.fail("TypeError expected when catching %s as specified in a " self.fail("TypeError expected when catching %s as specified in a "
"tuple" % type(object_)) "tuple" % type(object_))

View File

@ -10,6 +10,7 @@ import unittest
from test.test_support import run_unittest from test.test_support import run_unittest
from repr import repr as r # Don't shadow builtin repr from repr import repr as r # Don't shadow builtin repr
from repr import Repr
def nestedTuple(nesting): def nestedTuple(nesting):
@ -34,6 +35,18 @@ class ReprTests(unittest.TestCase):
expected = repr(s)[:13] + "..." + repr(s)[-14:] expected = repr(s)[:13] + "..." + repr(s)[-14:]
eq(r(s), expected) eq(r(s), expected)
def test_tuple(self):
eq = self.assertEquals
eq(r((1,)), "(1,)")
t3 = (1, 2, 3)
eq(r(t3), "(1, 2, 3)")
r2 = Repr()
r2.maxtuple = 2
expected = repr(t3)[:-2] + "...)"
eq(r2.repr(t3), expected)
def test_container(self): def test_container(self):
from array import array from array import array
from collections import deque from collections import deque

View File

@ -1,4 +1,7 @@
import unittest import unittest
import struct
import sys
from test import test_support, string_tests from test import test_support, string_tests
@ -88,6 +91,15 @@ class StrTest(
self.assertEqual(str8(Foo9("foo")), "string") self.assertEqual(str8(Foo9("foo")), "string")
self.assertEqual(str(Foo9("foo")), "not unicode") self.assertEqual(str(Foo9("foo")), "not unicode")
def test_expandtabs_overflows_gracefully(self):
# This test only affects 32-bit platforms because expandtabs can only take
# an int as the max value, not a 64-bit C long. If expandtabs is changed
# to take a 64-bit long, this test should apply to all platforms.
if sys.maxint > (1 << 32) or struct.calcsize('P') != 4:
return
self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxint)
def test_main(): def test_main():
test_support.run_unittest(StrTest) test_support.run_unittest(StrTest)

View File

@ -190,6 +190,15 @@ class TimeRETests(unittest.TestCase):
"locale data that contains regex metacharacters is not" "locale data that contains regex metacharacters is not"
" properly escaped") " properly escaped")
def test_whitespace_substitution(self):
# When pattern contains whitespace, make sure it is taken into account
# so as to not allow to subpatterns to end up next to each other and
# "steal" characters from each other.
pattern = self.time_re.pattern('%j %H')
self.failUnless(not re.match(pattern, "180"))
self.failUnless(re.match(pattern, "18 0"))
class StrptimeTests(unittest.TestCase): class StrptimeTests(unittest.TestCase):
"""Tests for _strptime.strptime.""" """Tests for _strptime.strptime."""
@ -463,8 +472,8 @@ class CalculationTests(unittest.TestCase):
"of the year") "of the year")
test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and " test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and "
"ending on Monday") "ending on Monday")
test_helper((2007, 01, 07), "First Sunday of 2007") test_helper((2007, 1, 7), "First Sunday of 2007")
test_helper((2007, 01, 14), "Second Sunday of 2007") test_helper((2007, 1, 14), "Second Sunday of 2007")
test_helper((2006, 12, 31), "Last Sunday of 2006") test_helper((2006, 12, 31), "Last Sunday of 2006")
test_helper((2006, 12, 24), "Second to last Sunday of 2006") test_helper((2006, 12, 24), "Second to last Sunday of 2006")

View File

@ -2,7 +2,8 @@ from _testcapi import test_structmembersType, \
CHAR_MAX, CHAR_MIN, UCHAR_MAX, \ CHAR_MAX, CHAR_MIN, UCHAR_MAX, \
SHRT_MAX, SHRT_MIN, USHRT_MAX, \ SHRT_MAX, SHRT_MIN, USHRT_MAX, \
INT_MAX, INT_MIN, UINT_MAX, \ INT_MAX, INT_MIN, UINT_MAX, \
LONG_MAX, LONG_MIN, ULONG_MAX LONG_MAX, LONG_MIN, ULONG_MAX, \
LLONG_MAX, LLONG_MIN, ULLONG_MAX
import warnings, unittest import warnings, unittest
from test import test_support from test import test_support
@ -39,6 +40,23 @@ class ReadWriteTests(unittest.TestCase):
ts.T_ULONG=ULONG_MAX ts.T_ULONG=ULONG_MAX
self.assertEquals(ts.T_ULONG, ULONG_MAX) self.assertEquals(ts.T_ULONG, ULONG_MAX)
## T_LONGLONG and T_ULONGLONG may not be present on some platforms
if hasattr(ts, 'T_LONGLONG'):
ts.T_LONGLONG=LLONG_MAX
self.assertEquals(ts.T_LONGLONG, LLONG_MAX)
ts.T_LONGLONG=LLONG_MIN
self.assertEquals(ts.T_LONGLONG, LLONG_MIN)
ts.T_ULONGLONG=ULLONG_MAX
self.assertEquals(ts.T_ULONGLONG, ULLONG_MAX)
## make sure these will accept a plain int as well as a long
ts.T_LONGLONG=3
self.assertEquals(ts.T_LONGLONG, 3)
ts.T_ULONGLONG=4
self.assertEquals(ts.T_ULONGLONG, 4)
class TestWarnings(unittest.TestCase): class TestWarnings(unittest.TestCase):
def has_warned(self, w): def has_warned(self, w):
self.assert_(w.category is RuntimeWarning) self.assert_(w.category is RuntimeWarning)

Some files were not shown because too many files have changed in this diff Show More