E582 Merged revisions 59541-59561 via svnmerge from · python/cpython@99170a5 · GitHub
[go: up one dir, main page]

Skip to content

Commit 99170a5

Browse files
committed
Merged revisions 59541-59561 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r59544 | raymond.hettinger | 2007-12-18 01:13:45 +0100 (Tue, 18 Dec 2007) | 1 line Add more namedtuple() test cases. Neaten the code and comments. ........ r59545 | christian.heimes | 2007-12-18 04:38:03 +0100 (Tue, 18 Dec 2007) | 3 lines Fixed for #1601: IDLE not working correctly on Windows (Py30a2/IDLE30a1) Amaury's ideas works great. Should we build the Python core with WINVER=0x0500 and _WIN32_WINNT=0x0500, too? ........ r59546 | christian.heimes | 2007-12-18 10:00:13 +0100 (Tue, 18 Dec 2007) | 1 line Make it a bit easier to test Tcl/Tk and idle from a build dir. ........ r59547 | christian.heimes | 2007-12-18 10:12:10 +0100 (Tue, 18 Dec 2007) | 1 line Removed several unused files from the PCbuild9 directory. They are relics from the past. ........ r59548 | raymond.hettinger | 2007-12-18 19:26:18 +0100 (Tue, 18 Dec 2007) | 29 lines Speed-up dictionary constructor by about 10%. New opcode, STORE_MAP saves the compiler from awkward stack manipulations and specializes for dicts using PyDict_SetItem instead of PyObject_SetItem. Old disassembly: 0 BUILD_MAP 0 3 DUP_TOP 4 LOAD_CONST 1 (1) 7 ROT_TWO 8 LOAD_CONST 2 ('x') 11 STORE_SUBSCR 12 DUP_TOP 13 LOAD_CONST 3 (2) 16 ROT_TWO 17 LOAD_CONST 4 ('y') 20 STORE_SUBSCR New disassembly: 0 BUILD_MAP 0 3 LOAD_CONST 1 (1) 6 LOAD_CONST 2 ('x') 9 STORE_MAP 10 LOAD_CONST 3 (2) 13 LOAD_CONST 4 ('y') 16 STORE_MAP ........ r59549 | thomas.heller | 2007-12-18 20:00:34 +0100 (Tue, 18 Dec 2007) | 2 lines Issue #1642: Fix segfault in ctypes when trying to delete attributes. ........ r59551 | guido.van.rossum | 2007-12-18 21:10:42 +0100 (Tue, 18 Dec 2007) | 2 lines Issue #1645 by Alberto Bertogli. Fix a comment. ........ r59553 | raymond.hettinger | 2007-12-18 22:24:09 +0100 (Tue, 18 Dec 2007) | 12 lines Give meaning to the oparg for BUILD_MAP: estimated size of the dictionary. Allows dictionaries to be pre-sized (upto 255 elements) saving time lost to re-sizes with their attendant mallocs and re-insertions. Has zero effect on small dictionaries (5 elements or fewer), a slight benefit for dicts upto 22 elements (because they had to resize once anyway), and more benefit for dicts upto 255 elements (saving multiple resizes during the build-up and reducing the number of collisions on the first insertions). Beyond 255 elements, there is no addional benefit. ........ r59554 | christian.heimes | 2007-12-18 22:56:09 +0100 (Tue, 18 Dec 2007) | 1 line Fixed #1649: IDLE error: dictionary changed size during iteration ........ r59557 | raymond.hettinger | 2007-12-18 23:21:27 +0100 (Tue, 18 Dec 2007) | 1 line Simplify and speedup _asdict() for named tuples. ........ r59558 | christian.heimes | 2007-12-19 00:22:54 +0100 (Wed, 19 Dec 2007) | 3 lines Applied patch #1635: Float patch for inf and nan on Windows (and other platforms). The patch unifies float("inf") and repr(float("inf")) on all platforms. ........ r59559 | raymond.hettinger | 2007-12-19 00:51:15 +0100 (Wed, 19 Dec 2007) | 1 line Users demand iterable input for named tuples. The author capitulates. ........ r59560 | raymond.hettinger | 2007-12-19 01:21:06 +0100 (Wed, 19 Dec 2007) | 1 line Beef-up tests for dict literals ........ r59561 | raymond.hettinger | 2007-12-19 01:27:21 +0100 (Wed, 19 Dec 2007) | 1 line Zap a duplicate line ........
1 parent 2c18161 commit 99170a5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+628
-4149
lines changed

Doc/c-api/utilities.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,22 @@ The following functions provide locale-independent string to number conversions.
10471047

10481048
See the Unix man page :manpage:`atof(2)` for details.
10491049

1050+
1051+
.. cfunction:: char * PyOS_stricmp(char *s1, char *s2)
1052+
1053+
Case insensitive comparsion of strings. The functions works almost
1054+
identical to :cfunc:`strcmp` except that it ignores the case.
1055+
1056+
.. versionadded:: 2.6
1057+
1058+
1059+
.. cfunction:: char * PyOS_strnicmp(char *s1, char *s2, Py_ssize_t size)
1060+
1061+
Case insensitive comparsion of strings. The functions works almost
1062+
identical to :cfunc:`strncmp` except that it ignores the case.
1063+
1064+
.. versionadded:: 2.6
1065+
10501066

10511067
.. _reflection:
10521068

Doc/library/collections.rst

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -421,27 +421,31 @@ Example::
421421

422422
__slots__ = ()
423423

424-
_fields = ('x', 'y')
425-
426424
def __new__(cls, x, y):
427425
return tuple.__new__(cls, (x, y))
428426

427+
_cast = classmethod(tuple.__new__)
428+
429429
def __repr__(self):
430430
return 'Point(x=%r, y=%r)' % self
431431

432-
def _asdict(self):
432+
def _asdict(t):
433433
'Return a new dict which maps field names to their values'
434-
return dict(zip(('x', 'y'), self))
434+
return {'x': t[0], 'y': t[1]}
435435

436436
def _replace(self, **kwds):
437437
'Return a new Point object replacing specified fields with new values'
438-
return Point(*map(kwds.get, ('x', 'y'), self))
438+
return Point._cast(map(kwds.get, ('x', 'y'), self))
439+
440+
@property
441+
def _fields(self):
442+
return ('x', 'y')
439443

440444
x = property(itemgetter(0))
441445
y = property(itemgetter(1))
442446

443447
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
444-
>>> p[0] + p[1] # indexable like the regular tuple (11, 22)
448+
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
445449
33
446450
>>> x, y = p # unpack like a regular tuple
447451
>>> x, y
@@ -456,33 +460,30 @@ by the :mod:`csv` or :mod:`sqlite3` modules::
456460

457461
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
458462

459-
from itertools import starmap
460463
import csv
461-
for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))):
464+
for emp in map(EmployeeRecord._cast, csv.reader(open("employees.csv", "rb"))):
462465
print(emp.name, emp.title)
463466

464467
import sqlite3
465468
conn = sqlite3.connect('/companydata')
466469
cursor = conn.cursor()
467470
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
468-
for emp in starmap(EmployeeRecord, cursor.fetchall()):
471+
for emp in map(EmployeeRecord._cast, cursor.fetchall()):
469472
print emp.name, emp.title
470473

471-
When casting a single record to a named tuple, use the star-operator [#]_ to unpack
472-
the values::
474+
In addition to the methods inherited from tuples, named tuples support
475+
three additonal methods and a read-only attribute.
473476

474-
>>> t = [11, 22]
475-
>>> Point(*t) # the star-operator unpacks any iterable object
476-
Point(x=11, y=22)
477+
.. method:: namedtuple._cast(iterable)
477478

478-
When casting a dictionary to a named tuple, use the double-star-operator::
479+
Class method returning a new instance taking the positional arguments from the *iterable*.
480+
Useful for casting existing sequences and iterables to named tuples:
479481

480-
>>> d = {'x': 11, 'y': 22}
481-
>>> Point(**d)
482-
Point(x=11, y=22)
482+
::
483483

484-
In addition to the methods inherited from tuples, named tuples support
485-
two additonal methods and a read-only attribute.
484+
>>> t = [11, 22]
485+
>>> Point._cast(t)
486+
Point(x=11, y=22)
486487

487488
.. method:: somenamedtuple._asdict()
488489

@@ -529,6 +530,12 @@ function:
529530
>>> getattr(p, 'x')
530531
11
531532

533+
When casting a dictionary to a named tuple, use the double-star-operator [#]_::
534+
535+
>>> d = {'x': 11, 'y': 22}
536+
>>> Point(**d)
537+
Point(x=11, y=22)
538+
532539
Since a named tuple is a regular Python class, it is easy to add or change
533540
functionality. For example, the display format can be changed by overriding
534541
the :meth:`__repr__` method:
@@ -551,5 +558,5 @@ and customizing it with :meth:`_replace`:
551558

552559
.. rubric:: Footnotes
553560

554-
.. [#] For information on the star-operator see
561+
.. [#] For information on the double-star-operator see
555562
:ref:`tut-unpacking-arguments` and :ref:`calls`.

Doc/library/functions.rst

Lines changed: 6 additions & 4 deletions
1004E
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,8 @@ available. They are listed here in alphabetical order.
435435

436436
Convert a string or a number to floating point. If the argument is a string, it
437437
must contain a possibly signed decimal or floating point number, possibly
438-
embedded in whitespace. Otherwise, the argument may be an integer
438+
embedded in whitespace. The argument may also be [+|-]nan or [+|-]inf.
439+
Otherwise, the argument may be a plain integer
439440
or a floating point number, and a floating point number with the same value
440441
(within Python's floating point precision) is returned. If no argument is
441442
given, returns ``0.0``.
@@ -447,9 +448,10 @@ available. They are listed here in alphabetical order.
447448
single: Infinity
448449

449450
When passing in a string, values for NaN and Infinity may be returned, depending
450-
on the underlying C library. The specific set of strings accepted which cause
451-
these values to be returned depends entirely on the C library and is known to
452-
vary.
451+
on the underlying C library. Float accepts the strings nan, inf and -inf for
452+
NaN and positive or negative infinity. The case and a leading + are ignored as
453+
well as a leading - is ignored for NaN. Float always represents NaN and infinity
454+
as nan, inf or -inf.
453455

454456
The float type is described in :ref:`typesnumeric`.
455457

Doc/library/stdtypes.rst

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ numeric operations have a higher priority than comparison operations):
285285
+---------------------+---------------------------------+-------+--------------------+
286286
| ``int(x)`` | *x* converted to integer | \(3) | :func:`int` |
287287
+---------------------+---------------------------------+-------+--------------------+
288-
| ``float(x)`` | *x* converted to floating point | | :func:`float` |
288+
| ``float(x)`` | *x* converted to floating point | \(6) | :func:`float` |
289289
+---------------------+---------------------------------+-------+--------------------+
290290
| ``complex(re, im)`` | a complex number with real part | | :func:`complex` |
291291
| | *re*, imaginary part *im*. | | |
@@ -329,6 +329,13 @@ Notes:
329329
as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module
330330
for well-defined conversions.
331331

332+
(6)
333+
float also accepts the strings "nan" and "inf" with an optional prefix "+"
334+
or "-" for Not a Number (NaN) and positive or negative infinity.
335+
336+
.. versionadded:: 2.6
337+
338+
332339
.. % XXXJH exceptions: overflow (when? what operations?) zerodivision
333340
334341

Include/Python.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@
114114
#include "eval.h"
115115

116116
#include "pystrtod.h"
117+
#include "pystrcmp.h"
117118

118119
/* _Py_Mangle is defined in compile.c */
119120
PyAPI_FUNC(PyObject*) _Py_Mangle(PyObject *p, PyObject *name);

Include/dictobject.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp);
123123
PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp);
124124
PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key);
125125
PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash);
126+
PyAPI_FUNC(PyObject *) _PyDict_NewPresized(Py_ssize_t minused);
126127

127128
/* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */
128129
PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);

Include/opcode.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ extern "C" {
3636
#define INPLACE_FLOOR_DIVIDE 28
3737
#define INPLACE_TRUE_DIVIDE 29
3838

39+
#define STORE_MAP 54
3940
#define INPLACE_ADD 55
4041
#define INPLACE_SUBTRACT 56
4142
#define INPLACE_MULTIPLY 57

Include/pyport.h

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,17 @@ extern "C" {
332332
#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE)
333333
#endif
334334

335+
/* High precision defintion of pi and e (Euler)
336+
* The values are taken from libc6's math.h.
337+
*/
338+
#ifndef Py_MATH_PI
339+
#define Py_MATH_PI 3.1415926535897932384626433832795029L
340+
#endif
341+
342+
#ifndef Py_MATH_E
343+
#define Py_MATH_E 2.7182818284590452353602874713526625L
344+
#endif
345+
335346
/* Py_IS_NAN(X)
336347
* Return 1 if float or double arg is a NaN, else 0.
337348
* Caution:
@@ -341,8 +352,12 @@ extern "C" {
341352
* a platform where it doesn't work.
342353
*/
343354
#ifndef Py_IS_NAN
355+
#ifdef HAVE_ISNAN
356+
#define Py_IS_NAN(X) isnan(X)
357+
#else
344358
#define Py_IS_NAN(X) ((X) != (X))
345359
#endif
360+
#endif
346361

347362
/* Py_IS_INFINITY(X)
348363
* Return 1 if float or double arg is an infinity, else 0.
@@ -353,17 +368,25 @@ extern "C" {
353368
* Override in pyconfig.h if you have a better spelling on your platform.
354369
*/
355370
#ifndef Py_IS_INFINITY
371+
#ifdef HAVE_ISINF
372+
#define Py_IS_INFINITY(X) isinf(X)
373+
#else
356374
#define Py_IS_INFINITY(X) ((X) && (X)*0.5 == (X))
357375
#endif
376+
#endif
358377

359378
/* Py_IS_FINITE(X)
360379
* Return 1 if float or double arg is neither infinite nor NAN, else 0.
361380
* Some compilers (e.g. VisualStudio) have intrisics for this, so a special
362381
* macro for this particular test is useful
363382
*/
364383
#ifndef Py_IS_FINITE
384+
#ifdef HAVE_ISFINITE
385+
#define Py_IS_FINITE(X) isfinite
386+
#else
365387
#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
366388
#endif
389+
#endif
367390

368391
/* HUGE_VAL is supposed to expand to a positive double infinity. Python
369392
* uses Py_HUGE_VAL instead because some platforms are broken in this
@@ -376,6 +399,15 @@ extern "C" {
376399
#define Py_HUGE_VAL HUGE_VAL
377400
#endif
378401

402+
/* Py_NAN
403+
* A value that evaluates to a NaN. On IEEE 754 platforms INF*0 or
404+
* INF/INF works. Define Py_NO_NAN in pyconfig.h if your platform
405+
* doesn't support NaNs.
406+
*/
407+
#if !defined(Py_NAN) && !defined(Py_NO_NAN)
408+
#define Py_NAN (Py_HUGE_VAL * 0.)
409+
#endif
410+
379411
/* Py_OVERFLOWED(X)
380412
* Return 1 iff a libm function overflowed. Set errno to 0 before calling
381413
* a libm function, and invoke this macro after, passing the function

Include/pystrcmp.h

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#ifndef Py_STRCMP_H
2+
#define Py_STRCMP_H
3+
4+
#ifdef __cplusplus
5+
extern "C" {
6+
#endif
7+
8+
PyAPI_FUNC(int) PyOS_mystrnicmp(const char *, const char *, Py_ssize_t);
9+
PyAPI_FUNC(int) PyOS_mystricmp(const char *, const char *);
10+
11+
#ifdef MS_WINDOWS
12+
#define PyOS_strnicmp strnicmp
13+
#define PyOS_stricmp stricmp
14+
#else
15+
#define PyOS_strnicmp PyOS_mystrnicmp
16+
#define PyOS_stricmp PyOS_mystricmp
17+
#endif
18+
19+
#ifdef __cplusplus
20+
}
21+
#endif
22+
23+
#endif /* !Py_STRCMP_H */

Lib/collections.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
11
__all__ = ['deque', 'defaultdict', 'namedtuple']
2-
3-
from _collections import deque, defaultdict
4-
from operator import itemgetter as _itemgetter
5-
from itertools import izip as _izip
6-
from keyword import iskeyword as _iskeyword
7-
import sys as _sys
8-
92
# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
103
# They should however be considered an integral part of collections.py.
114
from _abcoll import *
125
import _abcoll
136
__all__ += _abcoll.__all__
147

8+
from _collections import deque, defaultdict
9+
from operator import itemgetter as _itemgetter
10+
from keyword import iskeyword as _iskeyword
11+
import sys as _sys
12+
1513
def namedtuple(typename, field_names, verbose=False):
1614
"""Returns a new subclass of tuple with named fields.
1715
1816
>>> Point = namedtuple('Point', 'x y')
1917
>>> Point.__doc__ # docstring for the new class
2018
'Point(x, y)'
2119
>>> p = Point(11, y=22) # instantiate with positional args or keywords
22-
>>> p[0] + p[1] # works just like the tuple (11, 22)
20+
>>> p[0] + p[1] # indexable like a plain tuple
2321
33
24-
>>> x, y = p # unpacks just like a tuple
22+
>>> x, y = p # unpack like a regular tuple
2523
>>> x, y
2624
(11, 22)
2725
>>> p.x + p.y # fields also accessable by name
@@ -58,31 +56,35 @@ def namedtuple(typename, field_names, verbose=False):
5856
# Create and fill-in the class template
5957
argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
6058
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
59+
dicttxt = ', '.join('%r: t[%d]' % B4A6 (name, pos) for pos, name in enumerate(field_names))
6160
template = '''class %(typename)s(tuple):
6261
'%(typename)s(%(argtxt)s)' \n
6362
__slots__ = () \n
64-
_fields = property(lambda self: %(field_names)r) \n
6563
def __new__(cls, %(argtxt)s):
6664
return tuple.__new__(cls, (%(argtxt)s)) \n
65+
_cast = classmethod(tuple.__new__) \n
6766
def __repr__(self):
6867
return '%(typename)s(%(reprtxt)s)' %% self \n
69-
def _asdict(self, dict=dict, zip=zip):
68+
def _asdict(t):
7069
'Return a new dict which maps field names to their values'
71-
return dict(zip(%(field_names)r, self)) \n
70+
return {%(dicttxt)s} \n
7271
def _replace(self, **kwds):
7372
'Return a new %(typename)s object replacing specified fields with new values'
74-
return %(typename)s(*map(kwds.get, %(field_names)r, self)) \n\n''' % locals()
73+
return %(typename)s._cast(map(kwds.get, %(field_names)r, self)) \n
74+
@property
75+
def _fields(self):
76+
return %(field_names)r \n\n''' % locals()
7577
for i, name in enumerate(field_names):
7678
template += ' %s = property(itemgetter(%d))\n' % (name, i)
7779
if verbose:
7880
print(template)
7981

8082
# Execute the template string in a temporary namespace
81-
namespace = dict(itemgetter=_itemgetter, zip=_izip)
83+
namespace = dict(itemgetter=_itemgetter)
8284
try:
8385
exec(template, namespace)
8486
except SyntaxError as e:
85-
raise SyntaxError(e.message + ':\n' + template)
87+
raise SyntaxError(e.msg + ':\n' + template) from e
8688
result = namespace[typename]
8789

8890
# For pickling to work, the __module__ variable needs to be set to the frame

0 commit comments

Comments
 (0)
0