1. andrea_crotti
  2. cpython

Commits

andrea_crotti  committed 9ad67b0 Merge

merge

  • Participants
  • Parent commits 5f3589c, 9d69a24
  • Branches pstats

Comments (0)

Files changed (41)

File Doc/glossary.rst

View file
       For more information about descriptors' methods, see :ref:`descriptors`.
 
    dictionary
-      An associative array, where arbitrary keys are mapped to values.  The keys
-      can be any object with :meth:`__hash__` function and :meth:`__eq__`
-      methods. Called a hash in Perl.
+      An associative array, where arbitrary keys are mapped to values.  The
+      keys can be any object with :meth:`__hash__` and :meth:`__eq__` methods.
+      Called a hash in Perl.
 
    docstring
       A string literal which appears as the first expression in a class,

File Doc/library/datetime.rst

View file
 .. classmethod:: date.fromtimestamp(timestamp)
 
    Return the local date corresponding to the POSIX timestamp, such as is returned
-   by :func:`time.time`.  This may raise :exc:`ValueError`, if the timestamp is out
+   by :func:`time.time`.  This may raise :exc:`OverflowError`, if the timestamp is out
    of the range of values supported by the platform C :c:func:`localtime` function.
    It's common for this to be restricted to years from 1970 through 2038.  Note
    that on non-POSIX systems that include leap seconds in their notion of a
    timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
 
+   .. versionchanged:: 3.3
+      Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
+      is out of the range of values supported by the platform C
+      :c:func:`localtime` function.
+
 
 .. classmethod:: date.fromordinal(ordinal)
 
    and then it's possible to have two timestamps differing by a second that yield
    identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
 
+   .. versionchanged:: 3.3
+      Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
+      is out of the range of values supported by the platform C
+      :c:func:`localtime` or :c:func:`gmtime` functions
+
 
 .. classmethod:: datetime.utcfromtimestamp(timestamp)
 
 
       timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)
 
+   .. versionchanged:: 3.3
+      Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
+      is out of the range of values supported by the platform C
+      :c:func:`gmtime` function.
+
 
 .. classmethod:: datetime.fromordinal(ordinal)
 

File Include/pytime.h

View file
      (tv_end.tv_usec - tv_start.tv_usec) * 0.000001)
 
 #ifndef Py_LIMITED_API
+/* Convert a number of seconds, int or float, to time_t. */
+PyAPI_FUNC(int) _PyTime_ObjectToTime_t(
+    PyObject *obj,
+    time_t *sec);
+
+/* Convert a number of seconds, int or float, to a timeval structure.
+   usec is in the range [0; 999999] and rounded towards zero.
+   For example, -1.2 is converted to (-2, 800000). */
+PyAPI_FUNC(int) _PyTime_ObjectToTimeval(
+    PyObject *obj,
+    time_t *sec,
+    long *usec);
+
 /* Convert a number of seconds, int or float, to a timespec structure.
-   nsec is always in the range [0; 999999999]. For example, -1.2 is converted
-   to (-2, 800000000). */
+   nsec is in the range [0; 999999999] and rounded towards zero.
+   For example, -1.2 is converted to (-2, 800000000). */
 PyAPI_FUNC(int) _PyTime_ObjectToTimespec(
     PyObject *obj,
     time_t *sec,

File Include/timefuncs.h

-/*  timefuncs.h
- */
-
-/* Utility function related to timemodule.c. */
-
-#ifndef TIMEFUNCS_H
-#define TIMEFUNCS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Cast double x to time_t, but raise ValueError if x is too large
- * to fit in a time_t.  ValueError is set on return iff the return
- * value is (time_t)-1 and PyErr_Occurred().
- */
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(time_t) _PyTime_DoubleToTimet(double x);
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif  /* TIMEFUNCS_H */

File Lib/aifc.py

View file
 
 import struct
 import builtins
+import warnings
 
 __all__ = ["Error", "open", "openfp"]
 
             kludge = 0
             if chunk.chunksize == 18:
                 kludge = 1
-                print('Warning: bad COMM chunk size')
+                warnings.warn('Warning: bad COMM chunk size')
                 chunk.chunksize = 23
             #DEBUG end
             self._comptype = chunk.read(4)
                     # a position 0 and name ''
                     self._markers.append((id, pos, name))
         except EOFError:
-            print('Warning: MARK chunk contains only', end=' ')
-            print(len(self._markers), end=' ')
-            if len(self._markers) == 1: print('marker', end=' ')
-            else: print('markers', end=' ')
-            print('instead of', nmarkers)
+            w = ('Warning: MARK chunk contains only %s marker%s instead of %s' %
+                 (len(self._markers), '' if len(self._markers) == 1 else 's',
+                  nmarkers))
+            warnings.warn(w)
 
 class Aifc_write:
     # Variables used in this class:

File Lib/datetime.py

View file
         converter = _time.localtime if tz is None else _time.gmtime
 
         t, frac = divmod(t, 1.0)
-        us = round(frac * 1e6)
+        us = int(frac * 1e6)
 
         # If timestamp is less than one microsecond smaller than a
         # full second, us can be rounded up to 1000000.  In this case,
     def utcfromtimestamp(cls, t):
         "Construct a UTC datetime from a POSIX timestamp (like time.time())."
         t, frac = divmod(t, 1.0)
-        us = round(frac * 1e6)
+        us = int(frac * 1e6)
 
         # If timestamp is less than one microsecond smaller than a
         # full second, us can be rounded up to 1000000.  In this case,

File Lib/logging/handlers.py

View file
                         dstAtRollover = time.localtime(newRolloverAt)[-1]
                         if dstNow != dstAtRollover:
                             if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
-                                newRolloverAt = newRolloverAt - 3600
+                                addend = -3600
                             else:           # DST bows out before next rollover, so we need to add an hour
-                                newRolloverAt = newRolloverAt + 3600
+                                addend = 3600
+                            newRolloverAt += addend
                     result = newRolloverAt
         return result
 
             self.stream.close()
             self.stream = None
         # get the time that this sequence started at and make it a TimeTuple
+        currentTime = int(time.time())
+        dstNow = time.localtime(currentTime)[-1]
         t = self.rolloverAt - self.interval
         if self.utc:
             timeTuple = time.gmtime(t)
         else:
             timeTuple = time.localtime(t)
+            dstThen = timeTuple[-1]
+            if dstNow != dstThen:
+                if dstNow:
+                    addend = 3600
+                else:
+                    addend = -3600
+                timeTuple = time.localtime(t + addend)
         dfn = self.rotation_filename(self.baseFilename + "." +
                                      time.strftime(self.suffix, timeTuple))
         if os.path.exists(dfn):
                 os.remove(s)
         self.mode = 'w'
         self.stream = self._open()
-        currentTime = int(time.time())
         newRolloverAt = self.computeRollover(currentTime)
         while newRolloverAt <= currentTime:
             newRolloverAt = newRolloverAt + self.interval
         #If DST changes and midnight or weekly rollover, adjust for this.
         if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
-            dstNow = time.localtime(currentTime)[-1]
             dstAtRollover = time.localtime(newRolloverAt)[-1]
             if dstNow != dstAtRollover:
                 if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
-                    newRolloverAt = newRolloverAt - 3600
+                    addend = -3600
                 else:           # DST bows out before next rollover, so we need to add an hour
-                    newRolloverAt = newRolloverAt + 3600
+                    addend = 3600
+                newRolloverAt += addend
         self.rolloverAt = newRolloverAt
 
 class WatchedFileHandler(logging.FileHandler):

File Lib/pickle.py

View file
         self.write(NONE)
     dispatch[type(None)] = save_none
 
+    def save_ellipsis(self, obj):
+        self.save_global(Ellipsis, 'Ellipsis')
+    dispatch[type(Ellipsis)] = save_ellipsis
+
+    def save_notimplemented(self, obj):
+        self.save_global(NotImplemented, 'NotImplemented')
+    dispatch[type(NotImplemented)] = save_notimplemented
+
     def save_bool(self, obj):
         if self.proto >= 2:
             self.write(obj and NEWTRUE or NEWFALSE)

File Lib/test/datetimetester.py

View file
         # exempt such platforms (provided they return reasonable
         # results!).
         for insane in -1e200, 1e200:
-            self.assertRaises(ValueError, self.theclass.fromtimestamp,
+            self.assertRaises(OverflowError, self.theclass.fromtimestamp,
                               insane)
 
     def test_today(self):
         self.verify_field_equality(expected, got)
 
     def test_microsecond_rounding(self):
-        # Test whether fromtimestamp "rounds up" floats that are less
-        # than 1/2 microsecond smaller than an integer.
         for fts in [self.theclass.fromtimestamp,
                     self.theclass.utcfromtimestamp]:
-            self.assertEqual(fts(0.9999999), fts(1))
-            self.assertEqual(fts(0.99999949).microsecond, 999999)
+            zero = fts(0)
+            self.assertEqual(zero.second, 0)
+            self.assertEqual(zero.microsecond, 0)
+            minus_one = fts(-1e-6)
+            self.assertEqual(minus_one.second, 59)
+            self.assertEqual(minus_one.microsecond, 999999)
+
+            t = fts(-1e-8)
+            self.assertEqual(t, minus_one)
+            t = fts(-9e-7)
+            self.assertEqual(t, minus_one)
+            t = fts(-1e-7)
+            self.assertEqual(t, minus_one)
+
+            t = fts(1e-7)
+            self.assertEqual(t, zero)
+            t = fts(9e-7)
+            self.assertEqual(t, zero)
+            t = fts(0.99999949)
+            self.assertEqual(t.second, 0)
+            self.assertEqual(t.microsecond, 999999)
+            t = fts(0.9999999)
+            self.assertEqual(t.second, 0)
+            self.assertEqual(t.microsecond, 999999)
 
     def test_insane_fromtimestamp(self):
         # It's possible that some platform maps time_t to double,
         # exempt such platforms (provided they return reasonable
         # results!).
         for insane in -1e200, 1e200:
-            self.assertRaises(ValueError, self.theclass.fromtimestamp,
+            self.assertRaises(OverflowError, self.theclass.fromtimestamp,
                               insane)
 
     def test_insane_utcfromtimestamp(self):
         # exempt such platforms (provided they return reasonable
         # results!).
         for insane in -1e200, 1e200:
-            self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
+            self.assertRaises(OverflowError, self.theclass.utcfromtimestamp,
                               insane)
     @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
     def test_negative_float_fromtimestamp(self):

File Lib/test/pickletester.py

View file
                 u = self.loads(s)
                 self.assertEqual(t, u)
 
+    def test_ellipsis(self):
+        for proto in protocols:
+            s = self.dumps(..., proto)
+            u = self.loads(s)
+            self.assertEqual(..., u)
+
+    def test_notimplemented(self):
+        for proto in protocols:
+            s = self.dumps(NotImplemented, proto)
+            u = self.loads(s)
+            self.assertEqual(NotImplemented, u)
+
     # Tests for protocol 2
 
     def test_proto(self):

File Lib/test/test_aifc.py

View file
-from test.support import findfile, run_unittest, TESTFN
+from test.support import findfile, run_unittest, TESTFN, unlink
 import unittest
 import os
 import io
+import struct
 
 import aifc
 
                 self.fout.close()
             except (aifc.Error, AttributeError):
                 pass
-        try:
-            os.remove(TESTFN)
-        except OSError:
-            pass
+        unlink(TESTFN)
+        unlink(TESTFN + '.aiff')
 
     def test_skipunknown(self):
         #Issue 2245
 
     def test_params(self):
         f = self.f = aifc.open(self.sndfilepath)
+        self.assertEqual(f.getfp().name, self.sndfilepath)
         self.assertEqual(f.getnchannels(), 2)
         self.assertEqual(f.getsampwidth(), 2)
         self.assertEqual(f.getframerate(), 48000)
 
     def test_read(self):
         f = self.f = aifc.open(self.sndfilepath)
+        self.assertEqual(f.readframes(0), b'')
         self.assertEqual(f.tell(), 0)
         self.assertEqual(f.readframes(2), b'\x00\x00\x00\x00\x0b\xd4\x0b\xd4')
         f.rewind()
         self.assertEqual(f.readframes(2), b'\x17t\x17t"\xad"\xad')
         f.setpos(pos0)
         self.assertEqual(f.readframes(2), b'\x00\x00\x00\x00\x0b\xd4\x0b\xd4')
+        with self.assertRaises(aifc.Error):
+            f.setpos(-1)
+        with self.assertRaises(aifc.Error):
+            f.setpos(f.getnframes() + 1)
 
     def test_write(self):
         f = self.f = aifc.open(self.sndfilepath)
         self.assertEqual(f.getparams()[0:3], fout.getparams()[0:3])
         self.assertEqual(fout.getcomptype(), b'ULAW')
         self.assertEqual(fout.getcompname(), b'foo')
-        # XXX: this test fails, not sure if it should succeed or not
-        # self.assertEqual(f.readframes(5), fout.readframes(5))
 
     def test_close(self):
         class Wrapfile(object):
 
     def test_write_header_comptype_sampwidth(self):
         for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
-            fout = self.fout = aifc.open(io.BytesIO(), 'wb')
+            fout = aifc.open(io.BytesIO(), 'wb')
             fout.setnchannels(1)
             fout.setframerate(1)
             fout.setcomptype(comptype, b'')
             fout.initfp(None)
 
     def test_write_markers_values(self):
-        fout = self.fout = aifc.open(io.BytesIO(), 'wb')
+        fout = aifc.open(io.BytesIO(), 'wb')
         self.assertEqual(fout.getmarkers(), None)
         fout.setmark(1, 0, b'foo1')
         fout.setmark(1, 1, b'foo2')
         with self.assertRaises(ValueError):
             aifc._write_string(f, b'too long' * 255)
 
+    def test_wrong_open_mode(self):
+        with self.assertRaises(aifc.Error):
+            aifc.open(TESTFN, 'wrong_mode')
+
+    def test_read_wrong_form(self):
+        b1 = io.BytesIO(b'WRNG' + struct.pack('>L', 0))
+        b2 = io.BytesIO(b'FORM' + struct.pack('>L', 4) + b'WRNG')
+        self.assertRaises(aifc.Error, aifc.open, b1)
+        self.assertRaises(aifc.Error, aifc.open, b2)
+
+    def test_read_no_comm_chunk(self):
+        b = io.BytesIO(b'FORM' + struct.pack('>L', 4) + b'AIFF')
+        self.assertRaises(aifc.Error, aifc.open, b)
+
+    def test_read_wrong_compression_type(self):
+        b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
+        b += b'COMM' + struct.pack('>LhlhhLL', 23, 0, 0, 0, 0, 0, 0)
+        b += b'WRNG' + struct.pack('B', 0)
+        self.assertRaises(aifc.Error, aifc.open, io.BytesIO(b))
+
+    def test_read_wrong_marks(self):
+        b = b'FORM' + struct.pack('>L', 4) + b'AIFF'
+        b += b'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0)
+        b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
+        b += b'MARK' + struct.pack('>LhB', 3, 1, 1)
+        with self.assertWarns(UserWarning):
+            f = aifc.open(io.BytesIO(b))
+        self.assertEqual(f.getmarkers(), None)
+
+    def test_read_comm_kludge_compname_even(self):
+        b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
+        b += b'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0)
+        b += b'NONE' + struct.pack('B', 4) + b'even' + b'\x00'
+        b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
+        with self.assertWarns(UserWarning):
+            f = aifc.open(io.BytesIO(b))
+        self.assertEqual(f.getcompname(), b'even')
+
+    def test_read_comm_kludge_compname_odd(self):
+        b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
+        b += b'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0)
+        b += b'NONE' + struct.pack('B', 3) + b'odd'
+        b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
+        with self.assertWarns(UserWarning):
+            f = aifc.open(io.BytesIO(b))
+        self.assertEqual(f.getcompname(), b'odd')
+
+    def test_write_params_raises(self):
+        fout = aifc.open(io.BytesIO(), 'wb')
+        wrong_params = (0, 0, 0, 0, b'WRNG', '')
+        self.assertRaises(aifc.Error, fout.setparams, wrong_params)
+        self.assertRaises(aifc.Error, fout.getparams)
+        self.assertRaises(aifc.Error, fout.setnchannels, 0)
+        self.assertRaises(aifc.Error, fout.getnchannels)
+        self.assertRaises(aifc.Error, fout.setsampwidth, 0)
+        self.assertRaises(aifc.Error, fout.getsampwidth)
+        self.assertRaises(aifc.Error, fout.setframerate, 0)
+        self.assertRaises(aifc.Error, fout.getframerate)
+        self.assertRaises(aifc.Error, fout.setcomptype, b'WRNG', '')
+        fout.aiff()
+        fout.setnchannels(1)
+        fout.setsampwidth(1)
+        fout.setframerate(1)
+        fout.setnframes(1)
+        fout.writeframes(b'\x00')
+        self.assertRaises(aifc.Error, fout.setparams, (1, 1, 1, 1, 1, 1))
+        self.assertRaises(aifc.Error, fout.setnchannels, 1)
+        self.assertRaises(aifc.Error, fout.setsampwidth, 1)
+        self.assertRaises(aifc.Error, fout.setframerate, 1)
+        self.assertRaises(aifc.Error, fout.setnframes, 1)
+        self.assertRaises(aifc.Error, fout.setcomptype, b'NONE', '')
+        self.assertRaises(aifc.Error, fout.aiff)
+        self.assertRaises(aifc.Error, fout.aifc)
+
+    def test_write_params_singles(self):
+        fout = aifc.open(io.BytesIO(), 'wb')
+        fout.aifc()
+        fout.setnchannels(1)
+        fout.setsampwidth(2)
+        fout.setframerate(3)
+        fout.setnframes(4)
+        fout.setcomptype(b'NONE', b'name')
+        self.assertEqual(fout.getnchannels(), 1)
+        self.assertEqual(fout.getsampwidth(), 2)
+        self.assertEqual(fout.getframerate(), 3)
+        self.assertEqual(fout.getnframes(), 0)
+        self.assertEqual(fout.tell(), 0)
+        self.assertEqual(fout.getcomptype(), b'NONE')
+        self.assertEqual(fout.getcompname(), b'name')
+        fout.writeframes(b'\x00' * 4 * fout.getsampwidth() * fout.getnchannels())
+        self.assertEqual(fout.getnframes(), 4)
+        self.assertEqual(fout.tell(), 4)
+
+    def test_write_params_bunch(self):
+        fout = aifc.open(io.BytesIO(), 'wb')
+        fout.aifc()
+        p = (1, 2, 3, 4, b'NONE', b'name')
+        fout.setparams(p)
+        self.assertEqual(fout.getparams(), p)
+        fout.initfp(None)
+
+    def test_write_header_raises(self):
+        fout = aifc.open(io.BytesIO(), 'wb')
+        self.assertRaises(aifc.Error, fout.close)
+        fout.setnchannels(1)
+        self.assertRaises(aifc.Error, fout.close)
+        fout.setsampwidth(1)
+        self.assertRaises(aifc.Error, fout.close)
+        fout.initfp(None)
+
+    def test_write_header_comptype_raises(self):
+        for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
+            fout = aifc.open(io.BytesIO(), 'wb')
+            fout.setsampwidth(1)
+            fout.setcomptype(comptype, b'')
+            self.assertRaises(aifc.Error, fout.close)
+            fout.initfp(None)
+
+    def test_write_markers_raises(self):
+        fout = aifc.open(io.BytesIO(), 'wb')
+        self.assertRaises(aifc.Error, fout.setmark, 0, 0, b'')
+        self.assertRaises(aifc.Error, fout.setmark, 1, -1, b'')
+        self.assertRaises(aifc.Error, fout.setmark, 1, 0, None)
+        self.assertRaises(aifc.Error, fout.getmark, 1)
+        fout.initfp(None)
+
+    def test_write_aiff_by_extension(self):
+        sampwidth = 2
+        fout = self.fout = aifc.open(TESTFN + '.aiff', 'wb')
+        fout.setparams((1, sampwidth, 1, 1, b'ULAW', b''))
+        frames = b'\x00' * fout.getnchannels() * sampwidth
+        fout.writeframes(frames)
+        fout.close()
+        f = self.f = aifc.open(TESTFN + '.aiff', 'rb')
+        self.assertEqual(f.getcomptype(), b'NONE')
+        f.close()
+
 
 def test_main():
     run_unittest(AIFCTest)

File Lib/test/test_ast.py

View file
     def test_AST_objects(self):
         x = ast.AST()
         self.assertEqual(x._fields, ())
+        x.foobar = 42
+        self.assertEqual(x.foobar, 42)
+        self.assertEqual(x.__dict__["foobar"], 42)
 
         with self.assertRaises(AttributeError):
             x.vararg
 
-        with self.assertRaises(AttributeError):
-            x.foobar = 21
-
-        with self.assertRaises(AttributeError):
-            ast.AST(lineno=2)
-
         with self.assertRaises(TypeError):
             # "_ast.AST constructor takes 0 positional arguments"
             ast.AST(2)

File Lib/test/test_cgi.py

View file
 
 class CgiTests(unittest.TestCase):
 
+    def test_escape(self):
+        self.assertEqual("test &amp; string", cgi.escape("test & string"))
+        self.assertEqual("&lt;test string&gt;", cgi.escape("<test string>"))
+        self.assertEqual("&quot;test string&quot;", cgi.escape('"test string"', True))
+
     def test_strict(self):
         for orig, expect in parse_strict_test_cases:
             # Test basic parsing

File Lib/test/test_logging.py

View file
 import struct
 import sys
 import tempfile
-from test.support import captured_stdout, run_with_locale, run_unittest, patch
-from test.support import TestHandler, Matcher
+from test.support import (captured_stdout, run_with_locale, run_unittest,
+                          patch, requires_zlib, TestHandler, Matcher)
 import textwrap
 import time
 import unittest
 import warnings
 import weakref
-import zlib
 try:
     import threading
     # The following imports are needed only for tests which
 except ImportError:
     win32evtlogutil = None
     win32evtlog = None
+try:
+    import zlib
+except ImportError:
+    pass
 
 
 class BaseTest(unittest.TestCase):
         self.assertFalse(os.path.exists(namer(self.fn + ".3")))
         rh.close()
 
+    @requires_zlib
     def test_rotator(self):
         def namer(name):
             return name + ".gz"

File Lib/test/test_re.py

View file
         self.assertEqual([item.group(0) for item in iter],
                          [":", "::", ":::"])
 
+        pat = re.compile(r":+")
+        iter = pat.finditer("a:b::c:::d", 1, 10)
+        self.assertEqual([item.group(0) for item in iter],
+                         [":", "::", ":::"])
+
+        pat = re.compile(r":+")
+        iter = pat.finditer("a:b::c:::d", pos=1, endpos=10)
+        self.assertEqual([item.group(0) for item in iter],
+                         [":", "::", ":::"])
+
+        pat = re.compile(r":+")
+        iter = pat.finditer("a:b::c:::d", endpos=10, pos=1)
+        self.assertEqual([item.group(0) for item in iter],
+                         [":", "::", ":::"])
+
+        pat = re.compile(r":+")
+        iter = pat.finditer("a:b::c:::d", pos=3, endpos=8)
+        self.assertEqual([item.group(0) for item in iter],
+                         ["::", "::"])
+
     def test_bug_926075(self):
         self.assertTrue(re.compile('bug_926075') is not
                      re.compile(b'bug_926075'))
         self.assertIsNotNone(re.search("123.*-", '123\U0010ffff-'))
         self.assertIsNotNone(re.search("123.*-", '123\xe9\u20ac\U0010ffff-'))
 
+    def test_compile(self):
+        # Test return value when given string and pattern as parameter
+        pattern = re.compile('random pattern')
+        self.assertIsInstance(pattern, re._pattern_type)
+        same_pattern = re.compile(pattern)
+        self.assertIsInstance(same_pattern, re._pattern_type)
+        self.assertIs(same_pattern, pattern)
+        # Test behaviour when not given a string or pattern as parameter
+        self.assertRaises(TypeError, re.compile, 0)
+
 def run_re_tests():
     from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR
     if verbose:

File Lib/test/test_sys.py

View file
         check = self.check_sizeof
         # _ast.AST
         import _ast
-        check(_ast.AST(), size(h + ''))
+        check(_ast.AST(), size(h + 'P'))
         # imp.NullImporter
         import imp
         check(imp.NullImporter(self.file.name), size(h + ''))

File Lib/test/test_time.py

View file
         # results!).
         for func in time.ctime, time.gmtime, time.localtime:
             for unreasonable in -1e200, 1e200:
-                self.assertRaises(ValueError, func, unreasonable)
+                self.assertRaises(OverflowError, func, unreasonable)
 
     def test_ctime_without_arg(self):
         # Not sure how to check the values, since the clock could tick
         for time_t in (-1, 2**30, 2**33, 2**60):
             try:
                 time.localtime(time_t)
-            except ValueError as err:
-                if str(err) == "timestamp out of range for platform time_t":
-                    self.skipTest("need 64-bit time_t")
-                else:
-                    raise
+            except OverflowError:
+                self.skipTest("need 64-bit time_t")
             except OSError:
                 invalid_time_t = time_t
                 break
 
 
 class TestPytime(unittest.TestCase):
+    def setUp(self):
+        self.invalid_values = (
+            -(2 ** 100), 2 ** 100,
+            -(2.0 ** 100.0), 2.0 ** 100.0,
+        )
+
+    def test_time_t(self):
+        from _testcapi import pytime_object_to_time_t
+        for obj, time_t in (
+            (0, 0),
+            (-1, -1),
+            (-1.0, -1),
+            (-1.9, -1),
+            (1.0, 1),
+            (1.9, 1),
+        ):
+            self.assertEqual(pytime_object_to_time_t(obj), time_t)
+
+        for invalid in self.invalid_values:
+            self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
+
+    def test_timeval(self):
+        from _testcapi import pytime_object_to_timeval
+        for obj, timeval in (
+            (0, (0, 0)),
+            (-1, (-1, 0)),
+            (-1.0, (-1, 0)),
+            (1e-6, (0, 1)),
+            (-1e-6, (-1, 999999)),
+            (-1.2, (-2, 800000)),
+            (1.1234560, (1, 123456)),
+            (1.1234569, (1, 123456)),
+            (-1.1234560, (-2, 876544)),
+            (-1.1234561, (-2, 876543)),
+        ):
+            self.assertEqual(pytime_object_to_timeval(obj), timeval)
+
+        for invalid in self.invalid_values:
+            self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
+
     def test_timespec(self):
         from _testcapi import pytime_object_to_timespec
         for obj, timespec in (
             (0, (0, 0)),
             (-1, (-1, 0)),
             (-1.0, (-1, 0)),
+            (1e-9, (0, 1)),
             (-1e-9, (-1, 999999999)),
             (-1.2, (-2, 800000000)),
-            (1.123456789, (1, 123456789)),
+            (1.1234567890, (1, 123456789)),
+            (1.1234567899, (1, 123456789)),
+            (-1.1234567890, (-2, 876543211)),
+            (-1.1234567891, (-2, 876543210)),
         ):
             self.assertEqual(pytime_object_to_timespec(obj), timespec)
 
-        for invalid in (-(2 ** 100), -(2.0 ** 100.0), 2 ** 100, 2.0 ** 100.0):
+        for invalid in self.invalid_values:
             self.assertRaises(OverflowError, pytime_object_to_timespec, invalid)
 
 

File Lib/test/test_unicode.py

View file
         self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
 
         # test various errors
-        self.assertRaises(TypeError, '{'.format_map)
-        self.assertRaises(TypeError, '}'.format_map)
-        self.assertRaises(TypeError, 'a{'.format_map)
-        self.assertRaises(TypeError, 'a}'.format_map)
-        self.assertRaises(TypeError, '{a'.format_map)
-        self.assertRaises(TypeError, '}a'.format_map)
+        self.assertRaises(TypeError, ''.format_map)
+        self.assertRaises(TypeError, 'a'.format_map)
+
+        self.assertRaises(ValueError, '{'.format_map, {})
+        self.assertRaises(ValueError, '}'.format_map, {})
+        self.assertRaises(ValueError, 'a{'.format_map, {})
+        self.assertRaises(ValueError, 'a}'.format_map, {})
+        self.assertRaises(ValueError, '{a'.format_map, {})
+        self.assertRaises(ValueError, '}a'.format_map, {})
 
         # issue #12579: can't supply positional params to format_map
         self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})

File Lib/test/test_zipimport.py

View file
             mod = zi.load_module(TESTPACK)
             self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)
 
+            existing_pack_path = __import__(TESTPACK).__path__[0]
+            expected_path_path = os.path.join(TEMP_ZIP, TESTPACK)
+            self.assertEqual(existing_pack_path, expected_path_path)
+
             self.assertEqual(zi.is_package(packdir + '__init__'), False)
             self.assertEqual(zi.is_package(packdir + TESTPACK2), True)
             self.assertEqual(zi.is_package(packdir2 + TESTMOD), False)

File Lib/tkinter/__init__.py

View file
     Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
     that constrain the type of the value returned from get()."""
     _default = ""
+    _tk = None
     def __init__(self, master=None, value=None, name=None):
         """Construct a variable
 
         If NAME matches an existing variable and VALUE is omitted
         then the existing value is retained.
         """
+        # check for type of NAME parameter to override weird error message
+        # raised from Modules/_tkinter.c:SetVar like:
+        # TypeError: setvar() takes exactly 3 arguments (2 given)
+        if name is not None and not isinstance(name, str):
+            raise TypeError("name must be a string")
         global _varnum
         if not master:
             master = _default_root
             self._name = 'PY_VAR' + repr(_varnum)
             _varnum += 1
         if value is not None:
-            self.set(value)
+            self.initialize(value)
         elif not self._tk.call("info", "exists", self._name):
-            self.set(self._default)
+            self.initialize(self._default)
     def __del__(self):
         """Unset the variable in Tcl."""
-        self._tk.globalunsetvar(self._name)
+        if (self._tk is not None and self._tk.call("info", "exists",
+                                                   self._name)):
+            self._tk.globalunsetvar(self._name)
     def __str__(self):
         """Return the name of the variable in Tcl."""
         return self._name
     def set(self, value):
         """Set the variable to VALUE."""
         return self._tk.globalsetvar(self._name, value)
+    initialize = set
     def get(self):
         """Return value of variable."""
         return self._tk.globalgetvar(self._name)
         """
         Variable.__init__(self, master, value, name)
 
-    def set(self, value):
-        """Set the variable to value, converting booleans to integers."""
-        if isinstance(value, bool):
-            value = int(value)
-        return Variable.set(self, value)
-
     def get(self):
         """Return the value of the variable as an integer."""
         return getint(self._tk.globalgetvar(self._name))
 
     def get(self):
         """Return the value of the variable as a bool."""
-        return self._tk.getboolean(self._tk.globalgetvar(self._name))
+        try:
+            return self._tk.getboolean(self._tk.globalgetvar(self._name))
+        except TclError:
+            raise ValueError("invalid literal for getboolean()")
 
 def mainloop(n=0):
     """Run the main loop of Tcl."""
 
 def getboolean(s):
     """Convert true and false to integer values 1 and 0."""
-    return _default_root.tk.getboolean(s)
+    try:
+        return _default_root.tk.getboolean(s)
+    except TclError:
+        raise ValueError("invalid literal for getboolean()")
 
 # Methods defined on both toplevel and interior widgets
 class Misc:
     getdouble = float
     def getboolean(self, s):
         """Return a boolean value for Tcl boolean values true and false given as parameter."""
-        return self.tk.getboolean(s)
+        try:
+            return self.tk.getboolean(s)
+        except TclError:
+            raise ValueError("invalid literal for getboolean()")
     def focus_set(self):
         """Direct input focus to this widget.
 

File Lib/tkinter/test/test_tkinter/test_variables.py

View file
+import unittest
+
+from tkinter import Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tk
+
+
+class Var(Variable):
+
+    _default = "default"
+    side_effect = False
+
+    def set(self, value):
+        self.side_effect = True
+        super().set(value)
+
+
+class TestBase(unittest.TestCase):
+
+    def setUp(self):
+        self.root = Tk()
+
+    def tearDown(self):
+        self.root.destroy()
+
+
+class TestVariable(TestBase):
+
+    def test_default(self):
+        v = Variable(self.root)
+        self.assertEqual("", v.get())
+        self.assertRegex(str(v), r"^PY_VAR(\d+)$")
+
+    def test_name_and_value(self):
+        v = Variable(self.root, "sample string", "varname")
+        self.assertEqual("sample string", v.get())
+        self.assertEqual("varname", str(v))
+
+    def test___del__(self):
+        self.assertFalse(self.root.call("info", "exists", "varname"))
+        v = Variable(self.root, "sample string", "varname")
+        self.assertTrue(self.root.call("info", "exists", "varname"))
+        del v
+        self.assertFalse(self.root.call("info", "exists", "varname"))
+
+    def test_dont_unset_not_existing(self):
+        self.assertFalse(self.root.call("info", "exists", "varname"))
+        v1 = Variable(self.root, name="name")
+        v2 = Variable(self.root, name="name")
+        del v1
+        self.assertFalse(self.root.call("info", "exists", "name"))
+        # shouldn't raise exception
+        del v2
+        self.assertFalse(self.root.call("info", "exists", "name"))
+
+    def test___eq__(self):
+        # values doesn't matter, only class and name are checked
+        v1 = Variable(self.root, name="abc")
+        v2 = Variable(self.root, name="abc")
+        self.assertEqual(v1, v2)
+
+        v3 = Variable(self.root, name="abc")
+        v4 = StringVar(self.root, name="abc")
+        self.assertNotEqual(v3, v4)
+
+    def test_invalid_name(self):
+        with self.assertRaises(TypeError):
+            Variable(self.root, name=123)
+
+    def test_initialize(self):
+        v = Var()
+        self.assertFalse(v.side_effect)
+        v.set("value")
+        self.assertTrue(v.side_effect)
+
+
+class TestStringVar(TestBase):
+
+    def test_default(self):
+        v = StringVar(self.root)
+        self.assertEqual("", v.get())
+
+    def test_get(self):
+        v = StringVar(self.root, "abc", "name")
+        self.assertEqual("abc", v.get())
+        self.root.globalsetvar("name", True)
+        self.assertEqual("1", v.get())
+
+
+class TestIntVar(TestBase):
+
+    def test_default(self):
+        v = IntVar(self.root)
+        self.assertEqual(0, v.get())
+
+    def test_get(self):
+        v = IntVar(self.root, 123, "name")
+        self.assertEqual(123, v.get())
+        self.root.globalsetvar("name", "345")
+        self.assertEqual(345, v.get())
+
+    def test_invalid_value(self):
+        v = IntVar(self.root, name="name")
+        self.root.globalsetvar("name", "value")
+        with self.assertRaises(ValueError):
+            v.get()
+        self.root.globalsetvar("name", "345.0")
+        with self.assertRaises(ValueError):
+            v.get()
+
+
+class TestDoubleVar(TestBase):
+
+    def test_default(self):
+        v = DoubleVar(self.root)
+        self.assertEqual(0.0, v.get())
+
+    def test_get(self):
+        v = DoubleVar(self.root, 1.23, "name")
+        self.assertAlmostEqual(1.23, v.get())
+        self.root.globalsetvar("name", "3.45")
+        self.assertAlmostEqual(3.45, v.get())
+
+    def test_get_from_int(self):
+        v = DoubleVar(self.root, 1.23, "name")
+        self.assertAlmostEqual(1.23, v.get())
+        self.root.globalsetvar("name", "3.45")
+        self.assertAlmostEqual(3.45, v.get())
+        self.root.globalsetvar("name", "456")
+        self.assertAlmostEqual(456, v.get())
+
+    def test_invalid_value(self):
+        v = DoubleVar(self.root, name="name")
+        self.root.globalsetvar("name", "value")
+        with self.assertRaises(ValueError):
+            v.get()
+
+
+class TestBooleanVar(TestBase):
+
+    def test_default(self):
+        v = BooleanVar(self.root)
+        self.assertEqual(False, v.get())
+
+    def test_get(self):
+        v = BooleanVar(self.root, True, "name")
+        self.assertAlmostEqual(True, v.get())
+        self.root.globalsetvar("name", "0")
+        self.assertAlmostEqual(False, v.get())
+
+    def test_invalid_value_domain(self):
+        v = BooleanVar(self.root, name="name")
+        self.root.globalsetvar("name", "value")
+        with self.assertRaises(ValueError):
+            v.get()
+        self.root.globalsetvar("name", "1.0")
+        with self.assertRaises(ValueError):
+            v.get()
+
+
+tests_gui = (TestVariable, TestStringVar, TestIntVar,
+             TestDoubleVar, TestBooleanVar)
+
+
+if __name__ == "__main__":
+    from test.support import run_unittest
+    run_unittest(*tests_gui)

File Lib/unittest/loader.py

View file
     TestClass = type(classname, (case.TestCase,), attrs)
     return suiteClass((TestClass(methodname),))
 
+def _jython_aware_splitext(path):
+    if path.lower().endswith('$py.class'):
+        return path[:-9]
+    return os.path.splitext(path)[0]
+
 
 class TestLoader(object):
     """
             return os.path.dirname(full_path)
 
     def _get_name_from_path(self, path):
-        path = os.path.splitext(os.path.normpath(path))[0]
+        path = _jython_aware_splitext(os.path.normpath(path))
 
         _relpath = os.path.relpath(path, self._top_level_dir)
         assert not os.path.isabs(_relpath), "Path must be within the project"
                     yield _make_failed_import_test(name, self.suiteClass)
                 else:
                     mod_file = os.path.abspath(getattr(module, '__file__', full_path))
-                    realpath = os.path.splitext(mod_file)[0]
-                    fullpath_noext = os.path.splitext(full_path)[0]
+                    realpath = _jython_aware_splitext(mod_file)
+                    fullpath_noext = _jython_aware_splitext(full_path)
                     if realpath.lower() != fullpath_noext.lower():
                         module_dir = os.path.dirname(realpath)
-                        mod_name = os.path.splitext(os.path.basename(full_path))[0]
+                        mod_name = _jython_aware_splitext(os.path.basename(full_path))
                         expected_dir = os.path.dirname(full_path)
                         msg = ("%r module incorrectly imported from %r. Expected %r. "
                                "Is this module globally installed?")

File Lib/unittest/main.py

View file
 """Unittest main program"""
 
 import sys
+import optparse
 import os
 
 from . import loader, runner
 def _convert_names(names):
     return [_convert_name(name) for name in names]
 
+
 class TestProgram(object):
     """A command-line program that runs a set of tests; this is primarily
        for making test modules conveniently executable.
             self._do_discovery(argv[2:])
             return
 
-        import getopt
-        long_opts = ['help', 'verbose', 'quiet', 'failfast', 'catch', 'buffer']
-        try:
-            options, args = getopt.getopt(argv[1:], 'hHvqfcb', long_opts)
-        except getopt.error as msg:
-            self.usageExit(msg)
-            return
-
-        for opt, value in options:
-            if opt in ('-h','-H','--help'):
-                self.usageExit()
-            if opt in ('-q','--quiet'):
-                self.verbosity = 0
-            if opt in ('-v','--verbose'):
-                self.verbosity = 2
-            if opt in ('-f','--failfast'):
-                if self.failfast is None:
-                    self.failfast = True
-                # Should this raise an exception if -f is not valid?
-            if opt in ('-c','--catch'):
-                if self.catchbreak is None:
-                    self.catchbreak = True
-                # Should this raise an exception if -c is not valid?
-            if opt in ('-b','--buffer'):
-                if self.buffer is None:
-                    self.buffer = True
-                # Should this raise an exception if -b is not valid?
+        parser = self._getOptParser()
+        options, args = parser.parse_args(argv[1:])
+        self._setAttributesFromOptions(options)
 
         if len(args) == 0 and self.module is None:
             # this allows "python -m unittest -v" to still work for
             self.test = self.testLoader.loadTestsFromNames(self.testNames,
                                                            self.module)
 
-    def _do_discovery(self, argv, Loader=loader.TestLoader):
-        # handle command line args for test discovery
-        self.progName = '%s discover' % self.progName
-        import optparse
+    def _getOptParser(self):
         parser = optparse.OptionParser()
         parser.prog = self.progName
         parser.add_option('-v', '--verbose', dest='verbose', default=False,
                           help='Verbose output', action='store_true')
+        parser.add_option('-q', '--quiet', dest='quiet', default=False,
+                          help='Quiet output', action='store_true')
+
         if self.failfast != False:
             parser.add_option('-f', '--failfast', dest='failfast', default=False,
                               help='Stop on first fail or error',
             parser.add_option('-b', '--buffer', dest='buffer', default=False,
                               help='Buffer stdout and stderr during tests',
                               action='store_true')
-        parser.add_option('-s', '--start-directory', dest='start', default='.',
-                          help="Directory to start discovery ('.' default)")
-        parser.add_option('-p', '--pattern', dest='pattern', default='test*.py',
-                          help="Pattern to match tests ('test*.py' default)")
-        parser.add_option('-t', '--top-level-directory', dest='top', default=None,
-                          help='Top level directory of project (defaults to start directory)')
+        return parser
 
-        options, args = parser.parse_args(argv)
-        if len(args) > 3:
-            self.usageExit()
-
-        for name, value in zip(('start', 'pattern', 'top'), args):
-            setattr(options, name, value)
-
+    def _setAttributesFromOptions(self, options):
         # only set options from the parsing here
         # if they weren't set explicitly in the constructor
         if self.failfast is None:
 
         if options.verbose:
             self.verbosity = 2
+        elif options.quiet:
+            self.verbosity = 0
+
+    def _addDiscoveryOptions(self, parser):
+        parser.add_option('-s', '--start-directory', dest='start', default='.',
+                          help="Directory to start discovery ('.' default)")
+        parser.add_option('-p', '--pattern', dest='pattern', default='test*.py',
+                          help="Pattern to match tests ('test*.py' default)")
+        parser.add_option('-t', '--top-level-directory', dest='top', default=None,
+                          help='Top level directory of project (defaults to start directory)')
+
+    def _do_discovery(self, argv, Loader=loader.TestLoader):
+        # handle command line args for test discovery
+        self.progName = '%s discover' % self.progName
+        parser = self._getOptParser()
+        self._addDiscoveryOptions(parser)
+
+        options, args = parser.parse_args(argv)
+        if len(args) > 3:
+            self.usageExit()
+
+        for name, value in zip(('start', 'pattern', 'top'), args):
+            setattr(options, name, value)
+
+        self._setAttributesFromOptions(options)
 
         start_dir = options.start
         pattern = options.pattern

File Lib/unittest/test/test_program.py

View file
         FakeRunner.test = None
         FakeRunner.raiseError = False
 
-    def testHelpAndUnknown(self):
-        program = self.program
-        def usageExit(msg=None):
-            program.msg = msg
-            program.exit = True
-        program.usageExit = usageExit
-
-        for opt in '-h', '-H', '--help':
-            program.exit = False
-            program.parseArgs([None, opt])
-            self.assertTrue(program.exit)
-            self.assertIsNone(program.msg)
-
-        program.parseArgs([None, '-$'])
-        self.assertTrue(program.exit)
-        self.assertIsNotNone(program.msg)
-
     def testVerbosity(self):
         program = self.program
 

File Misc/ACKS

View file
 Michael Kremer
 Fabian Kreutz
 Cédric Krier
+Pedro Kroger
 Hannu Krosing
 Andrej Krpic
 Ivan Krstić
 Alain Leufroy
 Mark Levinson
 William Lewis
+Akira Li
 Xuanji Li
 Robert van Liere
 Ross Light
 Dom Mitchell
 Dustin J. Mitchell
 Zubin Mithra
+Florian Mladitsch
 Doug Moen
 The Dragon De Monsyne
 Skip Montanaro
 Rich Salz
 Kevin Samborn
 Adrian Sampson
+James Sanders
 Ilya Sandler
 Mark Sapiro
 Ty Sarna

File Misc/NEWS

View file
 Core and Builtins
 -----------------
 
+- Give the ast.AST class a __dict__.
+
 - Issue #1469629: Allow cycles through an object's __dict__ slot to be
   collected. (For example if ``x.__dict__ is x``).
 
 Library
 -------
 
+- Issue #14180: time.ctime(), gmtime(), time.localtime(),
+  datetime.date.fromtimestamp(), datetime.datetime.fromtimestamp() and
+  datetime.datetime.utcfromtimestamp() now raises an OverflowError, instead of
+  a ValueError, if the timestamp does not fit in time_t.
+
+- Issue #14180: datetime.datetime.fromtimestamp() and
+  datetime.datetime.utcfromtimestamp() now round microseconds towards zero
+  instead of rounding to nearest with ties going away from zero.
+
+- Issue #10543: Fix unittest test discovery with Jython bytecode files.
+
+- Issue #1178863: Separate initialisation from setting when initializing
+  Tkinter.Variables; harmonize exceptions to ValueError; only delete variables
+  that have not been deleted; assert that variable names are strings.
+
+- Issue #14104: Implement time.monotonic() on Mac OS X, patch written by
+  Nicholas Riley.
+
+- Issue #13394: the aifc module now uses warnings.warn() to signal warnings.
+
 - Issue #14252: Fix subprocess.Popen.terminate() to not raise an error under
   Windows when the child process has already exited.
 
 - Issue #14212: The re module didn't retain a reference to buffers it was
   scanning, resulting in segfaults.
 
+- Issue #14259: The finditer() method of re objects did not take any
+  keyword arguments, contrary to the documentation.
+
 
 What's New in Python 3.3.0 Alpha 1?
 ===================================

File Modules/_datetimemodule.c

View file
 
 #include <time.h>
 
-#include "_time.h"
-
 /* Differentiate between building the core module and building extension
  * modules.
  */
 
 /* Return new date from localtime(t). */
 static PyObject *
-date_local_from_time_t(PyObject *cls, double ts)
+date_local_from_object(PyObject *cls, PyObject *obj)
 {
     struct tm *tm;
     time_t t;
     PyObject *result = NULL;
 
-    t = _PyTime_DoubleToTimet(ts);
-    if (t == (time_t)-1 && PyErr_Occurred())
+    if (_PyTime_ObjectToTime_t(obj, &t) == -1)
         return NULL;
+
     tm = localtime(&t);
     if (tm)
         result = PyObject_CallFunction(cls, "iii",
 static PyObject *
 date_fromtimestamp(PyObject *cls, PyObject *args)
 {
-    double timestamp;
+    PyObject *timestamp;
     PyObject *result = NULL;
 
-    if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
-        result = date_local_from_time_t(cls, timestamp);
+    if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
+        result = date_local_from_object(cls, timestamp);
     return result;
 }
 
  * to get that much precision (e.g., C time() isn't good enough).
  */
 static PyObject *
-datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
+datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
                         PyObject *tzinfo)
 {
     time_t timet;
-    double fraction;
-    int us;
-
-    timet = _PyTime_DoubleToTimet(timestamp);
-    if (timet == (time_t)-1 && PyErr_Occurred())
+    long us;
+
+    if (_PyTime_ObjectToTimeval(timestamp, &timet, &us) == -1)
         return NULL;
-    fraction = timestamp - (double)timet;
-    us = (int)round_to_long(fraction * 1e6);
-    if (us < 0) {
-        /* Truncation towards zero is not what we wanted
-           for negative numbers (Python's mod semantics) */
-        timet -= 1;
-        us += 1000000;
-    }
-    /* If timestamp is less than one microsecond smaller than a
-     * full second, round up. Otherwise, ValueErrors are raised
-     * for some floats. */
-    if (us == 1000000) {
-        timet += 1;
-        us = 0;
-    }
     return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
 }
 
 datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
 {
     PyObject *self;
-    double timestamp;
+    PyObject *timestamp;
     PyObject *tzinfo = Py_None;
     static char *keywords[] = {"timestamp", "tz", NULL};
 
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
+    if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
                                       keywords, &timestamp, &tzinfo))
         return NULL;
     if (check_tzinfo_subclass(tzinfo) < 0)
 static PyObject *
 datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
 {
-    double timestamp;
+    PyObject *timestamp;
     PyObject *result = NULL;
 
-    if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
+    if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
         result = datetime_from_timestamp(cls, gmtime, timestamp,
                                          Py_None);
     return result;

File Modules/_pickle.c

View file
 }
 
 static int
+save_ellipsis(PicklerObject *self, PyObject *obj)
+{
+    PyObject *str = PyUnicode_FromString("Ellipsis");
+    if (str == NULL)
+        return -1;
+    return save_global(self, Py_Ellipsis, str);
+}
+
+static int
+save_notimplemented(PicklerObject *self, PyObject *obj)
+{
+    PyObject *str = PyUnicode_FromString("NotImplemented");
+    if (str == NULL)
+        return -1;
+    return save_global(self, Py_NotImplemented, str);
+}
+
+static int
 save_pers(PicklerObject *self, PyObject *obj, PyObject *func)
 {
     PyObject *pid = NULL;
         status = save_none(self, obj);
         goto done;
     }
+    else if (obj == Py_Ellipsis) {
+        status = save_ellipsis(self, obj);
+        goto done;
+    }
+    else if (obj == Py_NotImplemented) {
+        status = save_notimplemented(self, obj);
+        goto done;
+    }
     else if (obj == Py_False || obj == Py_True) {
         status = save_bool(self, obj);
         goto done;

File Modules/_sre.c

View file
 
 /* see sre.h for object declarations */
 static PyObject*pattern_new_match(PatternObject*, SRE_STATE*, int);
-static PyObject*pattern_scanner(PatternObject*, PyObject*);
+static PyObject*pattern_scanner(PatternObject*, PyObject*, PyObject* kw);
 
 static int
 sre_literal_template(int charsize, char* ptr, Py_ssize_t len)
 
 #if PY_VERSION_HEX >= 0x02020000
 static PyObject*
-pattern_finditer(PatternObject* pattern, PyObject* args)
+pattern_finditer(PatternObject* pattern, PyObject* args, PyObject* kw)
 {
     PyObject* scanner;
     PyObject* search;
     PyObject* iterator;
 
-    scanner = pattern_scanner(pattern, args);
+    scanner = pattern_scanner(pattern, args, kw);
     if (!scanner)
         return NULL;
 
     {"findall", (PyCFunction) pattern_findall, METH_VARARGS|METH_KEYWORDS,
         pattern_findall_doc},
 #if PY_VERSION_HEX >= 0x02020000
-    {"finditer", (PyCFunction) pattern_finditer, METH_VARARGS,
+    {"finditer", (PyCFunction) pattern_finditer, METH_VARARGS|METH_KEYWORDS,
         pattern_finditer_doc},
 #endif
-    {"scanner", (PyCFunction) pattern_scanner, METH_VARARGS},
+    {"scanner", (PyCFunction) pattern_scanner, METH_VARARGS|METH_KEYWORDS},
     {"__copy__", (PyCFunction) pattern_copy, METH_NOARGS},
     {"__deepcopy__", (PyCFunction) pattern_deepcopy, METH_O},
     {NULL, NULL}
 };
 
 static PyObject*
-pattern_scanner(PatternObject* pattern, PyObject* args)
+pattern_scanner(PatternObject* pattern, PyObject* args, PyObject* kw)
 {
     /* create search state object */
 
     PyObject* string;
     Py_ssize_t start = 0;
     Py_ssize_t end = PY_SSIZE_T_MAX;
-    if (!PyArg_ParseTuple(args, "O|nn:scanner", &string, &start, &end))
+    static char* kwlist[] = { "source", "pos", "endpos", NULL };
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:scanner", kwlist,
+                                     &string, &start, &end))
         return NULL;
 
     /* create scanner object */

File Modules/_testcapimodule.c

View file
     return PyLong_FromLong(r);
 }
 
+static PyObject*
+_PyLong_FromTime_t(time_t value)
+{
+#if defined(HAVE_LONG_LONG) && SIZEOF_TIME_T == SIZEOF_LONG_LONG
+    return PyLong_FromLongLong(value);
+#else
+    assert(sizeof(time_t) <= sizeof(long));
+    return PyLong_FromLong(value);
+#endif
+}
+
+static PyObject *
+test_pytime_object_to_time_t(PyObject *self, PyObject *args)
+{
+    PyObject *obj;
+    time_t sec;
+    if (!PyArg_ParseTuple(args, "O:pytime_object_to_time_t", &obj))
+        return NULL;
+    if (_PyTime_ObjectToTime_t(obj, &sec) == -1)
+        return NULL;
+    return _PyLong_FromTime_t(sec);
+}
+
+static PyObject *
+test_pytime_object_to_timeval(PyObject *self, PyObject *args)
+{
+    PyObject *obj;
+    time_t sec;
+    long usec;
+    if (!PyArg_ParseTuple(args, "O:pytime_object_to_timeval", &obj))
+        return NULL;
+    if (_PyTime_ObjectToTimeval(obj, &sec, &usec) == -1)
+        return NULL;
+    return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), usec);
+}
+
 static PyObject *
 test_pytime_object_to_timespec(PyObject *self, PyObject *args)
 {
         return NULL;
     if (_PyTime_ObjectToTimespec(obj, &sec, &nsec) == -1)
         return NULL;
-#if defined(HAVE_LONG_LONG) && SIZEOF_TIME_T == SIZEOF_LONG_LONG
-    return Py_BuildValue("Ll", (PY_LONG_LONG)sec, nsec);
-#else
-    assert(sizeof(time_t) <= sizeof(long));
-    return Py_BuildValue("ll", (long)sec, nsec);
-#endif
+    return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), nsec);
 }
 
 
      METH_NOARGS},
     {"crash_no_current_thread", (PyCFunction)crash_no_current_thread, METH_NOARGS},
     {"run_in_subinterp",        run_in_subinterp,                METH_VARARGS},
+    {"pytime_object_to_time_t", test_pytime_object_to_time_t,  METH_VARARGS},
+    {"pytime_object_to_timeval", test_pytime_object_to_timeval,  METH_VARARGS},
     {"pytime_object_to_timespec", test_pytime_object_to_timespec,  METH_VARARGS},
     {NULL, NULL} /* sentinel */
 };

File Modules/_time.c

-#include "Python.h"
-#include "_time.h"
-
-/* Exposed in timefuncs.h. */
-time_t
-_PyTime_DoubleToTimet(double x)
-{
-    time_t result;
-    double diff;
-
-    result = (time_t)x;
-    /* How much info did we lose?  time_t may be an integral or
-     * floating type, and we don't know which.  If it's integral,
-     * we don't know whether C truncates, rounds, returns the floor,
-     * etc.  If we lost a second or more, the C rounding is
-     * unreasonable, or the input just doesn't fit in a time_t;
-     * call it an error regardless.  Note that the original cast to
-     * time_t can cause a C error too, but nothing we can do to
-     * work around that.
-     */
-    diff = x - (double)result;
-    if (diff <= -1.0 || diff >= 1.0) {
-        PyErr_SetString(PyExc_ValueError,
-                        "timestamp out of range for platform time_t");
-        result = (time_t)-1;
-    }
-    return result;
-}

File Modules/_time.h

-/* XXX: It is probably best to move timefuncs.h content in here, and
-   remove it but user code may rely on it. */
-#include "timefuncs.h"

File Modules/posixmodule.c

View file
 #endif /* HAVE_UNAME */
 
 
-static int
-extract_time(PyObject *t, time_t* sec, long* nsec)
-{
-    time_t intval;
-    if (PyFloat_Check(t)) {
-        double d = PyFloat_AsDouble(t);
-        double mod;
-        *sec = (time_t)d;
-        mod = fmod(d, 1.0);
-        mod *= 1e9;
-        *nsec = (long)mod;
-        return 0;
-    }
-#if SIZEOF_TIME_T > SIZEOF_LONG
-    intval = PyLong_AsUnsignedLongLongMask(t);
-#else
-    intval = PyLong_AsLong(t);
-#endif
-    if (intval == -1 && PyErr_Occurred())
-        return -1;
-    *sec = intval;
-    *nsec = 0;
-    return 0;
-}
-
 PyDoc_STRVAR(posix_utime__doc__,
 "utime(path[, (atime, mtime)])\n\
 Set the access and modified time of the file to the given values.\n\
         goto done;
     }
     else {
-        if (extract_time(PyTuple_GET_ITEM(arg, 0),
-                         &atimesec, &ansec) == -1)
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 0),
+                                     &atimesec, &ansec) == -1)
             goto done;
         time_t_to_FILE_TIME(atimesec, ansec, &atime);
-        if (extract_time(PyTuple_GET_ITEM(arg, 1),
-                         &mtimesec, &mnsec) == -1)
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 1),
+                                     &mtimesec, &mnsec) == -1)
             goto done;
         time_t_to_FILE_TIME(mtimesec, mnsec, &mtime);
     }
         return NULL;
     }
     else {
-        if (extract_time(PyTuple_GET_ITEM(arg, 0),
-                         &atime, &ansec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 0),
+                                     &atime, &ansec) == -1) {
             Py_DECREF(opath);
             return NULL;
         }
-        if (extract_time(PyTuple_GET_ITEM(arg, 1),
-                         &mtime, &mnsec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 1),
+                                     &mtime, &mnsec) == -1) {
             Py_DECREF(opath);
             return NULL;
         }
         return NULL;
     }
     else {
-        if (extract_time(PyTuple_GET_ITEM(arg, 0),
-                &atime, &ansec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 0),
+                                     &atime, &ansec) == -1) {
             return NULL;
         }
-        if (extract_time(PyTuple_GET_ITEM(arg, 1),
-                &mtime, &mnsec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 1),
+                                     &mtime, &mnsec) == -1) {
             return NULL;
         }
         Py_BEGIN_ALLOW_THREADS
         return NULL;
     }
     else {
-        if (extract_time(PyTuple_GET_ITEM(arg, 0),
-                &atime, &ansec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 0),
+                                     &atime, &ansec) == -1) {
             Py_DECREF(opath);
             return NULL;
         }
-        if (extract_time(PyTuple_GET_ITEM(arg, 1),
-                &mtime, &mnsec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 1),
+                                     &mtime, &mnsec) == -1) {
             Py_DECREF(opath);
             return NULL;
         }
         return NULL;
     }
     else {
-        if (extract_time(PyTuple_GET_ITEM(arg, 0),
-                         &atime, &ansec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 0),
+                                     &atime, &ansec) == -1) {
             Py_DECREF(opath);
             return NULL;
         }
-        if (extract_time(PyTuple_GET_ITEM(arg, 1),
-                         &mtime, &mnsec) == -1) {
+        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(arg, 1),
+                                     &mtime, &mnsec) == -1) {
             Py_DECREF(opath);
             return NULL;
         }

File Modules/selectmodule.c

View file
     PyObject *ret = NULL;
     PyObject *tout = Py_None;
     fd_set ifdset, ofdset, efdset;
-    double timeout;
     struct timeval tv, *tvp;
-    long seconds;
     int imax, omax, emax, max;
     int n;
 
         return NULL;
     }
     else {
-        timeout = PyFloat_AsDouble(tout);
-        if (timeout == -1 && PyErr_Occurred())
+        long usec;
+        if (_PyTime_ObjectToTimeval(tout, &tv.tv_sec, &usec) == -1)
             return NULL;
-        if (timeout > (double)LONG_MAX) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "timeout period too long");
+        tv.tv_usec = usec;
+        if (tv.tv_sec < 0) {
+            PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
             return NULL;
         }
-        if (timeout < 0) {
-            PyErr_SetString(PyExc_ValueError,
-                        "timeout must be non-negative");
-            return NULL;
-        }
-        seconds = (long)timeout;
-        timeout = timeout - (double)seconds;
-        tv.tv_sec = seconds;
-        tv.tv_usec = (long)(timeout * 1E6);
         tvp = &tv;
     }
 
     PyObject *result = NULL;
     struct kevent *evl = NULL;
     struct kevent *chl = NULL;
-    struct timespec timeoutspec;
+    struct timespec timeout;
     struct timespec *ptimeoutspec;
 
     if (self->kqfd < 0)
         ptimeoutspec = NULL;
     }
     else if (PyNumber_Check(otimeout)) {
-        double timeout;
-        long seconds;
+        if (_PyTime_ObjectToTimespec(otimeout,
+                                     &timeout.tv_sec, &timeout.tv_nsec) == -1)
+            return NULL;
 
-        timeout = PyFloat_AsDouble(otimeout);
-        if (timeout == -1 && PyErr_Occurred())
-            return NULL;
-        if (timeout > (double)LONG_MAX) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "timeout period too long");
-            return NULL;
-        }
-        if (timeout < 0) {
+        if (timeout.tv_sec < 0) {
             PyErr_SetString(PyExc_ValueError,
                             "timeout must be positive or None");
             return NULL;
         }
-
-        seconds = (long)timeout;
-        timeout = timeout - (double)seconds;
-        timeoutspec.tv_sec = seconds;
-        timeoutspec.tv_nsec = (long)(timeout * 1E9);
-        ptimeoutspec = &timeoutspec;
+        ptimeoutspec = &timeout;
     }
     else {
         PyErr_Format(PyExc_TypeError,

File Modules/timemodule.c

View file
 /* Time module */
 
 #include "Python.h"
-#include "_time.h"
 
 #include <ctype.h>
 
 #include <sys/time.h>
 #endif
 
+#if defined(__APPLE__)
+#include <mach/mach_time.h>
+#endif
+
 /* Forward declarations */
 static int floatsleep(double);
 static double floattime(void);
         whent = time(NULL);
     }
     else {
-        double d = PyFloat_AsDouble(ot);
-        if (PyErr_Occurred())
-            return 0;
-        whent = _PyTime_DoubleToTimet(d);
-        if (whent == (time_t)-1 && PyErr_Occurred())
+        if (_PyTime_ObjectToTime_t(ot, &whent) == -1)
             return 0;
     }
     *pwhen = whent;
 calls is valid.");
 
 #if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) \
-    || (defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC))
+    || (defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)) \
+    || (defined(__APPLE__))
 #  define HAVE_PYTIME_MONOTONIC
 #endif
 
 {
 #if defined(MS_WINDOWS) && !defined(__BORLANDC__)
     return win32_clock(0);
+#elif defined(__APPLE__)
+    uint64_t time = mach_absolute_time();
+    double secs;
+
+    static mach_timebase_info_data_t timebase;
+    if (timebase.denom == 0)
+      mach_timebase_info(&timebase);
+
+    secs = (double)time * timebase.numer / timebase.denom * 1e-9;
+
+    return PyFloat_FromDouble(secs);
 #else
     static int clk_index = 0;
     clockid_t clk_ids[] = {

File PCbuild/pythoncore.vcproj

View file
 				>
 			</File>
 			<File
-				RelativePath="..\Modules\_time.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\_time.h"
-				>
-			</File>
-			<File
 				RelativePath="..\Modules\_weakref.c"
 				>
 			</File>

File Parser/asdl_c.py

View file
 
     def visitModule(self, mod):
         self.emit("""
+typedef struct {
+    PyObject_HEAD
+    PyObject *dict;
+} AST_object;
+
 static int
 ast_type_init(PyObject *self, PyObject *args, PyObject *kw)
 {
     {NULL}
 };
 
+static PyGetSetDef ast_type_getsets[] = {
+    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
+    {NULL}
+};
+
 static PyTypeObject AST_type = {
     PyVarObject_HEAD_INIT(&PyType_Type, 0)
     "_ast.AST",
-    sizeof(PyObject),
+    sizeof(AST_object),
     0,
     0,                       /* tp_dealloc */
     0,                       /* tp_print */
     0,                       /* tp_iternext */
     ast_type_methods,        /* tp_methods */
     0,                       /* tp_members */
-    0,                       /* tp_getset */
+    ast_type_getsets,        /* tp_getset */
     0,                       /* tp_base */
     0,                       /* tp_dict */
     0,                       /* tp_descr_get */
     0,                       /* tp_descr_set */
-    0,                       /* tp_dictoffset */
+    offsetof(AST_object, dict),/* tp_dictoffset */
     (initproc)ast_type_init, /* tp_init */
     PyType_GenericAlloc,     /* tp_alloc */
     PyType_GenericNew,       /* tp_new */
         p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
         f = open(p, "w")
         f.write(auto_gen_msg)
+        f.write('#include <stddef.h>\n')
+        f.write('\n')
         f.write('#include "Python.h"\n')
         f.write('#include "%s-ast.h"\n' % mod.name)
         f.write('\n')

File Python/Python-ast.c

View file
 /* File automatically generated by Parser/asdl_c.py. */
 
+#include <stddef.h>
+