8000 Merged revisions 58211-58220 via svnmerge from · python/cpython@8ce81f7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8ce81f7

Browse files
committed
Merged revisions 58211-58220 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r58211 | facundo.batista | 2007-09-19 19:53:25 +0200 (Wed, 19 Sep 2007) | 4 lines Issue #1772851. Optimization of __hash__ to behave better for big big numbers. ........ r58216 | raymond.hettinger | 2007-09-20 05:03:43 +0200 (Thu, 20 Sep 2007) | 1 line Fit nits ........ r58217 | georg.brandl | 2007-09-20 10:44:59 +0200 (Thu, 20 Sep 2007) | 2 lines alternate -> alternative. ........ r58218 | georg.brandl | 2007-09-20 18:06:07 +0200 (Thu, 20 Sep 2007) | 2 lines Patch #1541463: optimize performance of cgi.FieldStorage operations. ........ r58219 | georg.brandl | 2007-09-20 18:45:27 +0200 (Thu, 20 Sep 2007) | 2 lines #1176: document that string methods don't take keyword args. ........ r58220 | thomas.wouters | 2007-09-20 19:35:10 +0200 (Thu, 20 Sep 2007) | 4 lines Try harder to stay within the 79-column limit. There's still two places that go (way) over, but those are harder to fix without suffering in readability. ........
1 parent 7ce29ca commit 8ce81f7

File tree

8 files changed

+117
-61
lines changed

8 files changed

+117
-61
lines changed

Doc/library/collections.rst

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -395,8 +395,8 @@ Setting the :attr:`default_factory` to :class:`set` makes the
395395

396396
.. _named-tuple-factory:
397397

398-
:func:`NamedTuple` factory function
399-
-----------------------------------
398+
:func:`NamedTuple` Factory Function for Tuples with Named Fields
399+
----------------------------------------------------------------
400400

401401
Named tuples assign meaning to each position in a tuple and allow for more readable,
402402
self-documenting code. They can be used wherever regular tuples are used, and
@@ -411,12 +411,12 @@ they add the ability to access fields by name instead of position index.
411411
method which lists the tuple contents in a ``name=value`` format.
412412

413413
The *fieldnames* are specified in a single string with each fieldname separated by
414-
a space and/or comma. Any valid Python identifier may be used for a field name.
414+
a space and/or comma. Any valid Python identifier may be used for a fieldname.
415415

416-
If *verbose* is true, the *NamedTuple* call will print the class definition.
416+
If *verbose* is true, will print the class definition.
417417

418418
*NamedTuple* instances do not have per-instance dictionaries, so they are
419-
lightweight, requiring no more memory than regular tuples.
419+
lightweight and require no more memory than regular tuples.
420420

421421
Example::
422422

@@ -467,7 +467,9 @@ an additonal method and an informational read-only attribute.
467467

468468
.. method:: somenamedtuple.replace(field, value)
469469

470-
Return a new instance of the named tuple replacing the named *field* with a new *value*::
470+
Return a new instance of the named tuple replacing the named *field* with a new *value*:
471+
472+
::
471473

472474
>>> p = Point(x=11, y=22)
473475
>>> p.__replace__('x', 33)
@@ -480,7 +482,9 @@ an additonal method and an informational read-only attribute.
480482

481483
Return a tuple of strings listing the field names. This is useful for introspection,
482484
for converting a named tuple instance to a dictionary, and for combining named tuple
483-
types to create new named tuple types::
485+
types to create new named tuple types:
486+
487+
::
484488

485489
>>> p.__fields__ # view the field names
486490
('x', 'y')

Doc/library/decimal.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -977,7 +977,7 @@ method. For example, ``C.exp(x)`` is equivalent to
977977

978978
The usual approach to working with decimals is to create :class:`Decimal`
979979
instances and then apply arithmetic operations which take place within the
980-
current context for the active thread. An alternate approach is to use context
980+
current context for the active thread. An alternative approach is to use context
981981
methods for calculating within a specific context. The methods are similar to
982982
those for the :class:`Decimal` class and are only briefly recounted here.
983983

Doc/library/stdtypes.rst

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -657,10 +657,13 @@ String Methods
657657

658658
.. index:: pair: string; methods
659659

660-
String objects support the methods listed below. In addition, Python's strings
661-
support the sequence type methods described in the :ref:`typesseq` section. To
662-
output formatted strings, see the :ref:`string-formatting` section. Also, see
663-
the :mod:`re` module for string functions based on regular expressions.
660+
String objects support the methods listed below. Note that none of these
661+
methods take keyword arguments.
662+
663+
In addition, Python's strings support the sequence type methods described in
664+
the :ref:`typesseq` section. To output formatted strings, see the
665+
:ref:`string-formatting` section. Also, see the :mod:`re` module for string
666+
functions based on regular expressions.
664667

665668
.. method:: str.capitalize()
666669

Doc/tutorial/inputoutput.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ having to load the entire file in memory. Only complete lines will be returned.
252252
>>> f.readlines()
253253
['This is the first line of the file.\n', 'Second line of the file\n']
254254

255-
An alternate approach to reading lines is to loop over the file object. This is
255+
An alternative approach to reading lines is to loop over the file object. This is
256256
memory efficient, fast, and leads to simpler code::
257257

258258
>>> for line in f:

Lib/cgi.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -604,23 +604,21 @@ def keys(self):
604604
"""Dictionary style keys() method."""
605605
if self.list is None:
606606
raise TypeError("not indexable")
607-
keys = []
608-
for item in self.list:
609-
if item.name not in keys: keys.append(item.name)
610-
return keys
607+
return list(set(item.name for item in self.list))
611608

612609
def __contains__(self, key):
613610
"""Dictionary style __contains__ method."""
614611
if self.list is None:
615612
raise TypeError("not indexable")
616-
for item in self.list:
617-
if item.name == key: return True
618-
return False
613+
return any(item.name == key for item in self.list)
619614

620615
def __len__(self):
621616
"""Dictionary style len(x) support."""
622617
return len(self.keys())
623618

619+
def __nonzero__(self):
620+
return bool(self.list)
621+
624622
def read_urlencoded(self):
625623
"""Internal: read data in query string format."""
626624
qs = self.fp.read(self.length)

Lib/decimal.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -786,10 +786,17 @@ def __hash__(self):
786786
if self._isnan():
787787
raise TypeError('Cannot hash a NaN value.')
788788
return hash(str(self))
789-
i = int(self)
790-
if self == Decimal(i):
791-
return hash(i)
792-
assert self.__bool__() # '-0' handled by integer case
789+
if not self:
790+
return 0
791+
if self._isinteger():
792+
op = _WorkRep(self.to_integral_value())
793+
# to make computation feasible for Decimals with large
794+
# exponent, we use the fact that hash(n) == hash(m) for
795+
# any two nonzero integers n and m such that (i) n and m
796+
# have the same sign, and (ii) n is congruent to m modulo
797+
# 2**64-1. So we can replace hash((-1)**s*c*10**e) with
798+
# hash((-1)**s*c*pow(10, e, 2**64-1).
799+
return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
793800
return hash(str(self.normalize()))
794801

795802
def as_tuple(self):

Lib/test/test_decimal.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -901,6 +901,38 @@ def test_copy_and_deepcopy_methods(self):
901901
def test_hash_method(self):
902902
#just that it's hashable
903903
hash(Decimal(23))
904+
905+
test_values = [Decimal(sign*(2**m + n))
906+
for m in [0, 14, 15, 16, 17, 30, 31,
907+
32, 33, 62, 63, 64, 65, 66]
908+
for n in range(-10, 10)
909+
for sign in [-1, 1]]
910+
test_values.extend([
911+
Decimal("-0"), # zeros
912+
Decimal("0.00"),
913+
Decimal("-0.000"),
914+
Decimal("0E10"),
915+
Decimal("-0E12"),
916+
Decimal("10.0"), # negative exponent
917+
Decimal("-23.00000"),
918+
Decimal("1230E100"), # positive exponent
919+
Decimal("-4.5678E50"),
920+
# a value for which hash(n) != hash(n % (2**64-1))
921+
# in Python pre-2.6
922+
Decimal(2**64 + 2**32 - 1),
923+
# selection of values which fail with the old (before
924+
# version 2.6) long.__hash__
925+
Decimal("1.634E100"),
926+
Decimal("90.697E100"),
927+
Decimal("188.83E100"),
928+
Decimal("1652.9E100"),
929+
Decimal("56531E100"),
930+
])
931+
932+
# check that hash(d) == hash(int(d)) for integral values
933+
for value in test_values:
934+
self.assertEqual(hash(value), hash(int(value)))
935+
904936
#the same hash that to an int
905937
self.assertEqual(hash(Decimal(23)), hash(23))
906938
self.assertRaises(TypeError, hash, Decimal('NaN'))

Python/ceval.c

Lines changed: 49 additions & 37 deletions
< 10000 td data-grid-cell-id="diff-c22186367cbe20233e843261998dc027ae5f1f8c0d2e778abfa454ae74cc59de-524-527-0" data-selected="false" role="gridcell" style="background-color:var(--bgColor-default);text-align:center" tabindex="-1" valign="top" class="focusable-grid-cell diff-line-number position-relative diff-line-number-neutral left-side">524
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@
2828
typedef unsigned long long uint64;
2929

3030
#if defined(__ppc__) /* <- Don't know if this is the correct symbol; this
31-
section should work for GCC on any PowerPC platform,
32-
irrespective of OS. POWER? Who knows :-) */
31+
section should work for GCC on any PowerPC
32+
platform, irrespective of OS.
33+
POWER? Who knows :-) */
3334

3435
#define READ_TIMESTAMP(var) ppc_getcounter(&var)
3536

@@ -93,7 +94,8 @@ static PyObject * call_function(PyObject ***, int);
9394
static PyObject * fast_function(PyObject *, PyObject ***, int, int, int);
9495
static PyObject * do_call(PyObject *, PyObject ***, int, int);
9596
static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int);
96-
static PyObject * update_keyword_args(PyObject *, int, PyObject ***,PyObject *);
97+
static PyObject * update_keyword_args(PyObject *, int, PyObject ***,
98+
PyObject *);
9799
static PyObject * update_star_args(int, int, PyObject *, PyObject ***);
98100
static PyObject * load_args(PyObject ***, int);
99101
#define CALL_FLAG_VAR 1
@@ -509,7 +511,8 @@ PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
509511
PyObject *
510512
PyEval_EvalFrame(PyFrameObject *f) {
511513
/* This is for backward compatibility with extension modules that
512-
used this API; core interpreter code should call PyEval_EvalFrameEx() */
514+
used this API; core interpreter code should call
515+
PyEval_EvalFrameEx() */
513516
return PyEval_EvalFrameEx(f, 0);
514517
}
515518

@@ -519,7 +522,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
519522
#ifdef DXPAIRS
520523
int lastopcode = 0;
521524
#endif
522-
register PyObject **stack_pointer; /* Next free slot in value stack */
525+
register PyObject **stack_pointer; /* Next free slot in value stack */
523526
register unsigned char *next_instr;
527
register int opcode; /* Current opcode */
525528
register int oparg; /* Current opcode argument, if any */
@@ -610,10 +613,10 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
610613
#define JUMPBY(x) (next_instr += (x))
611614

612615
/* OpCode prediction macros
613-
Some opcodes tend to come in pairs thus making it possible to predict
614-
the second code when the first is run. For example, COMPARE_OP is often
615-
followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, those opcodes are often
616-
followed by a POP_TOP.
616+
Some opcodes tend to come in pairs thus making it possible to
617+
predict the second code when the first is run. For example,
618+
COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And,
619+
those opcodes are often followed by a POP_TOP.
617620
618621
Verifying the prediction costs a single high-speed test of register
619622
variable against a constant. If the pairing was good, then the
@@ -660,11 +663,13 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
660663
#define PUSH(v) { (void)(BASIC_PUSH(v), \
661664
lltrace && prtrace(TOP(), "push")); \
662665
assert(STACK_LEVEL() <= co->co_stacksize); }
663-
#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP())
666+
#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
667+
BASIC_POP())
664668
#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
665669
lltrace && prtrace(TOP(), "stackadj")); \
666670
assert(STACK_LEVEL() <= co->co_stacksize); }
667-
#define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], "ext_pop"), *--(STACK_POINTER))
671+
#define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], \
672+
"ext_pop"), *--(STACK_POINTER))
668673
#else
669674
#define PUSH(v) BASIC_PUSH(v)
670675
#define POP() BASIC_POP()
@@ -1568,7 +1573,8 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
15681573
if ((x = f->f_locals) != NULL) {
15691574
if ((err = PyObject_DelItem(x, w)) != 0)
15701575
format_exc_check_arg(PyExc_NameError,
1571-
NAME_ERROR_MSG ,w);
1576+
NAME_ERROR_MSG,
1577+
w);
15721578
break;
15731579
}
15741580
PyErr_Format(PyExc_SystemError,
@@ -1579,24 +1585,28 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
15791585
PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
15801586
case UNPACK_SEQUENCE:
15811587
v = POP();
1582-
if (PyTuple_CheckExact(v) && PyTuple_GET_SIZE(v) == oparg) {
1583-
PyObject **items = ((PyTupleObject *)v)->ob_item;
1588+
if (PyTuple_CheckExact(v) &&
1589+
PyTuple_GET_SIZE(v) == oparg) {
1590+
PyObject **items = \
1591+
((PyTupleObject *)v)->ob_item;
15841592
while (oparg--) {
15851593
w = items[oparg];
15861594
Py_INCREF(w);
15871595
PUSH(w);
15881596
}
15891597
Py_DECREF(v);
15901598
continue;
1591-
} else if (PyList_CheckExact(v) && PyList_GET_SIZE(v) == oparg) {
1592-
PyObject **items = ((PyListObject *)v)->ob_item;
1599+
} else if (PyList_CheckExact(v) &&
1600+
PyList_GET_SIZE(v) == oparg) {
1601+
PyObject **items = \
1602+
((PyListObject *)v)->ob_item;
15931603
while (oparg--) {
15941604
w = items[oparg];
15951605
Py_INCREF(w);
15961606
PUSH(w);
15971607
}
15981608
} else if (unpack_iterable(v, oparg, -1,
1599-
stack_pointer + oparg)) {
1609+
stack_pointer + oparg)) {
16001610
stack_pointer += oparg;
16011611
} else {
16021612
/* unpack_iterable() raised an exception */
@@ -1669,7 +1679,8 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
16691679
else {
16701680
x = PyObject_GetItem(v, w);
16711681
if (x == NULL && PyErr_Occurred()) {
1672-
if (!PyErr_ExceptionMatches(PyExc_KeyError))
1682+
if (!PyErr_ExceptionMatches(
1683+
PyExc_KeyError))
16731684
break;
16741685
PyErr_Clear();
16751686
}
@@ -1681,7 +1692,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
16811692
if (x == NULL) {
16821693
format_exc_check_arg(
16831694
PyExc_NameError,
1684-
NAME_ERROR_MSG ,w);
1695+
NAME_ERROR_MSG, w);
16851696
break;
16861697
}
16871698
}
@@ -1782,13 +1793,10 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
17821793
UNBOUNDLOCAL_ERROR_MSG,
17831794
v);
17841795
} else {
1785-
v = PyTuple_GET_ITEM(
1786-
co->co_freevars,
1787-
oparg - PyTuple_GET_SIZE(co->co_cellvars));
1788-
format_exc_check_arg(
1789-
PyExc_NameError,
1790-
UNBOUNDFREE_ERROR_MSG,
1791-
v);
1796+
v = PyTuple_GET_ITEM(co->co_freevars, oparg -
1797+
PyTuple_GET_SIZE(co->co_cellvars));
1798+
format_exc_check_arg(PyExc_NameError,
1799+
UNBOUNDFREE_ERROR_MSG, v);
17921800
}
17931801
break;
17941802

@@ -2046,7 +2054,8 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
20462054
continue;
20472055
}
20482056
if (PyErr_Occurred()) {
2049-
if (!PyErr_ExceptionMatches(PyExc_StopIteration))
2057+
if (!PyErr_ExceptionMatches(
2058+
PyExc_StopIteration))
20502059
break;
20512060
PyErr_Clear();
20522061
}
@@ -2072,9 +2081,10 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
20722081
case SETUP_LOOP:
20732082
case SETUP_EXCEPT:
20742083
case SETUP_FINALLY:
2075-
/* NOTE: If you add any new block-setup opcodes that are
2076-
not try/except/finally handlers, you may need to
2077-
update the PyGen_NeedsFinalizing() function. */
2084+
/* NOTE: If you add any new block-setup opcodes that
2085+
are not try/except/finally handlers, you may need
2086+
to update the PyGen_NeedsFinalizing() function.
2087+
*/
20782088

20792089
PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
20802090
STACK_LEVEL());
@@ -3968,8 +3978,9 @@ string_concatenate(PyObject *v, PyObject *w,
39683978
if (v->ob_refcnt == 2) {
39693979
/* In the common case, there are 2 references to the value
39703980
* stored in 'variable' when the += is performed: one on the
3971-
* value stack (in 'v') and one still stored in the 'variable'.
3972-
* We try to delete the variable now to reduce the refcnt to 1.
3981+
* value stack (in 'v') and one still stored in the
3982+
* 'variable'. We try to delete the variable now to reduce
3983+
* the refcnt to 1.
39733984
*/
39743985
switch (*next_instr) {
39753986
case STORE_FAST:
@@ -3982,7 +3993,8 @@ string_concatenate(PyObject *v, PyObject *w,
39823993
}
39833994
case STORE_DEREF:
39843995
{
3985-
PyObject **freevars = f->f_localsplus + f->f_code->co_nlocals;
3996+
PyObject **freevars = (f->f_localsplus +
3997+
f->f_code->co_nlocals);
39863998
PyObject *c = freevars[PEEKARG()];
39873999
if (PyCell_GET(c) == v)
39884000
PyCell_Set(c, NULL);
@@ -4010,10 +4022,10 @@ string_concatenate(PyObject *v, PyObject *w,
40104022
*/
40114023
if (_PyString_Resize(&v, new_len) != 0) {
40124024
/* XXX if _PyString_Resize() fails, 'v' has been
4013-
* deallocated so it cannot be put back into 'variable'.
4014-
* The MemoryError is raised when there is no value in
4015-
* 'variable', which might (very remotely) be a cause
4016-
* of incompatibilities.
4025+
* deallocated so it cannot be put back into
4026+
* 'variable'. The MemoryError is raised when there
4027+
* is no value in 'variable', which might (very
4028+
* remotely) be a cause of incompatibilities.
40174029
*/
40184030
return NULL;
40194031
}

0 commit comments

Comments
 (0)
0