2054
2085
diff -r 3d0686d90f55 Doc/howto/functional.rst
2055
2086
--- a/Doc/howto/functional.rst
2056
2087
+++ b/Doc/howto/functional.rst
2088
@@ -181,26 +181,26 @@
2090
An iterator is an object representing a stream of data; this object returns the
2091
data one element at a time. A Python iterator must support a method called
2092
-``__next__()`` that takes no arguments and always returns the next element of
2093
-the stream. If there are no more elements in the stream, ``__next__()`` must
2094
-raise the ``StopIteration`` exception. Iterators don't have to be finite,
2095
-though; it's perfectly reasonable to write an iterator that produces an infinite
2097
+:meth:`~iterator.__next__` that takes no arguments and always returns the next
2098
+element of the stream. If there are no more elements in the stream,
2099
+:meth:`~iterator.__next__` must raise the :exc:`StopIteration` exception.
2100
+Iterators don't have to be finite, though; it's perfectly reasonable to write
2101
+an iterator that produces an infinite stream of data.
2103
The built-in :func:`iter` function takes an arbitrary object and tries to return
2104
an iterator that will return the object's contents or elements, raising
2105
:exc:`TypeError` if the object doesn't support iteration. Several of Python's
2106
built-in data types support iteration, the most common being lists and
2107
-dictionaries. An object is called an **iterable** object if you can get an
2109
+dictionaries. An object is called :term:`iterable` if you can get an iterator
2112
You can experiment with the iteration interface manually:
2117
+ >>> it #doctest: +ELLIPSIS
2118
<...iterator object at ...>
2120
+ >>> it.__next__() # same as next(it)
2127
Python expects iterable objects in several different contexts, the most
2128
-important being the ``for`` statement. In the statement ``for X in Y``, Y must
2129
-be an iterator or some object for which ``iter()`` can create an iterator.
2130
-These two statements are equivalent::
2131
+important being the :keyword:`for` statement. In the statement ``for X in Y``,
2132
+Y must be an iterator or some object for which :func:`iter` can create an
2133
+iterator. These two statements are equivalent::
2137
@@ -246,16 +246,16 @@
2058
2138
iterator argument and will return the largest or smallest element. The ``"in"``
2059
2139
and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
2060
2140
X is found in the stream returned by the iterator. You'll run into obvious
2061
2141
-problems if the iterator is infinite; ``max()``, ``min()``, and ``"not in"``
2062
+problems if the iterator is infinite; ``max()``, ``min()``
2142
+problems if the iterator is infinite; :func:`max`, :func:`min`
2063
2143
will never return, and if the element X never appears in the stream, the
2064
2144
-``"in"`` operator won't return either.
2065
2145
+``"in"`` and ``"not in"`` operators won't return either.
2067
2147
Note that you can only go forward in an iterator; there's no way to get the
2068
2148
previous element, reset the iterator, or make a copy of it. Iterator objects
2149
can optionally provide these additional capabilities, but the iterator protocol
2150
-only specifies the ``next()`` method. Functions may therefore consume all of
2151
-the iterator's output, and if you need to do something different with the same
2152
-stream, you'll have to create a new iterator.
2153
+only specifies the :meth:`~iterator.__next__` method. Functions may therefore
2154
+consume all of the iterator's output, and if you need to do something different
2155
+with the same stream, you'll have to create a new iterator.
2159
@@ -267,15 +267,11 @@
2162
Calling :func:`iter` on a dictionary returns an iterator that will loop over the
2165
-.. not a doctest since dict ordering varies across Pythons
2168
+dictionary's keys::
2170
>>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
2171
... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
2173
+ >>> for key in m: #doctest: +SKIP
2174
... print(key, m[key])
2178
Applying :func:`iter` to a dictionary always loops over the keys, but
2179
dictionaries have methods that return other iterators. If you want to iterate
2180
over values or key/value pairs, you can explicitly call the
2181
-:meth:`values` or :meth:`items` methods to get an appropriate iterator.
2182
+:meth:`~dict.values` or :meth:`~dict.items` methods to get an appropriate iterator.
2184
The :func:`dict` constructor can accept an iterator that returns a finite stream
2185
of ``(key, value)`` tuples:
2188
{'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}
2190
-Files also support iteration by calling the ``readline()`` method until there
2191
-are no more lines in the file. This means you can read each line of a file like
2193
+Files also support iteration by calling the :meth:`~io.TextIOBase.readline`
2194
+method until there are no more lines in the file. This means you can read each
2195
+line of a file like this::
2198
# do something for each line
2199
@@ -410,12 +406,9 @@
2200
lengths of all the sequences. If you have two lists of length 3, the output
2201
list is 9 elements long:
2204
- :options: +NORMALIZE_WHITESPACE
2208
- >>> [(x,y) for x in seq1 for y in seq2]
2209
+ >>> [(x, y) for x in seq1 for y in seq2] #doctest: +NORMALIZE_WHITESPACE
2210
[('a', 1), ('a', 2), ('a', 3),
2211
('b', 1), ('b', 2), ('b', 3),
2212
('c', 1), ('c', 2), ('c', 3)]
2214
comprehension below is a syntax error, while the second one is correct::
2217
- [ x,y for x in seq1 for y in seq2]
2218
+ [x, y for x in seq1 for y in seq2]
2220
- [ (x,y) for x in seq1 for y in seq2]
2221
+ [(x, y) for x in seq1 for y in seq2]
2225
@@ -448,15 +441,13 @@
2227
Here's the simplest example of a generator function:
2230
+ >>> def generate_ints(N):
2231
+ ... for i in range(N):
2234
- def generate_ints(N):
2235
- for i in range(N):
2238
-Any function containing a ``yield`` keyword is a generator function; this is
2239
-detected by Python's :term:`bytecode` compiler which compiles the function
2240
-specially as a result.
2241
+Any function containing a :keyword:`yield` keyword is a generator function;
2242
+this is detected by Python's :term:`bytecode` compiler which compiles the
2243
+function specially as a result.
2245
When you call a generator function, it doesn't return a single value; instead it
2246
returns a generator object that supports the iterator protocol. On executing
2247
@@ -464,12 +455,13 @@
2248
``return`` statement. The big difference between ``yield`` and a ``return``
2249
statement is that on reaching a ``yield`` the generator's state of execution is
2250
suspended and local variables are preserved. On the next call to the
2251
-generator's ``.__next__()`` method, the function will resume executing.
2252
+generator's :meth:`~generator.__next__` method, the function will resume
2255
Here's a sample usage of the ``generate_ints()`` generator:
2257
>>> gen = generate_ints(3)
2259
+ >>> gen #doctest: +ELLIPSIS
2260
<generator object generate_ints at ...>
2263
@@ -491,17 +483,19 @@
2264
``return`` the generator cannot return any further values. ``return`` with a
2265
value, such as ``return 5``, is a syntax error inside a generator function. The
2266
end of the generator's results can also be indicated by raising
2267
-``StopIteration`` manually, or by just letting the flow of execution fall off
2268
+:exc:`StopIteration` manually, or by just letting the flow of execution fall off
2269
the bottom of the function.
2271
You could achieve the effect of generators manually by writing your own class
2272
and storing all the local variables of the generator as instance variables. For
2273
example, returning a list of integers could be done by setting ``self.count`` to
2274
-0, and having the ``__next__()`` method increment ``self.count`` and return it.
2275
+0, and having the :meth:`~iterator.__next__` method increment ``self.count`` and
2277
However, for a moderately complicated generator, writing a corresponding class
2278
can be much messier.
2280
-The test suite included with Python's library, ``test_generators.py``, contains
2281
+The test suite included with Python's library,
2282
+:source:`Lib/test/test_generators.py`, contains
2283
a number of more interesting examples. Here's one generator that implements an
2284
in-order traversal of a tree using generators recursively. ::
2286
@@ -544,23 +538,23 @@
2287
The parentheses aren't always necessary, but it's easier to always add them
2288
instead of having to remember when they're needed.
2290
-(PEP 342 explains the exact rules, which are that a ``yield``-expression must
2291
+(:pep:`342` explains the exact rules, which are that a ``yield``-expression must
2292
always be parenthesized except when it occurs at the top-level expression on the
2293
right-hand side of an assignment. This means you can write ``val = yield i``
2294
but have to use parentheses when there's an operation, as in ``val = (yield i)
2297
-Values are sent into a generator by calling its ``send(value)`` method. This
2298
-method resumes the generator's code and the ``yield`` expression returns the
2299
-specified value. If the regular ``__next__()`` method is called, the ``yield``
2301
+Values are sent into a generator by calling its :meth:`send(value)
2302
+<generator.send>` method. This method resumes the generator's code and the
2303
+``yield`` expression returns the specified value. If the regular
2304
+:meth:`~generator.__next__` method is called, the ``yield`` returns ``None``.
2306
Here's a simple counter that increments by 1 and allows changing the value of
2307
the internal counter.
2311
- def counter (maximum):
2312
+ def counter(maximum):
2316
@@ -572,16 +566,16 @@
2318
And here's an example of changing the counter:
2320
- >>> it = counter(10)
2322
+ >>> it = counter(10) #doctest: +SKIP
2323
+ >>> next(it) #doctest: +SKIP
2326
+ >>> next(it) #doctest: +SKIP
2329
+ >>> it.send(8) #doctest: +SKIP
2332
+ >>> next(it) #doctest: +SKIP
2335
+ >>> next(it) #doctest: +SKIP
2336
Traceback (most recent call last):
2337
File "t.py", line 15, in ?
2339
@@ -589,20 +583,23 @@
2341
Because ``yield`` will often be returning ``None``, you should always check for
2342
this case. Don't just use its value in expressions unless you're sure that the
2343
-``send()`` method will be the only method used resume your generator function.
2344
+:meth:`~generator.send` method will be the only method used resume your
2345
+generator function.
2347
-In addition to ``send()``, there are two other new methods on generators:
2348
+In addition to :meth:`~generator.send`, there are two other methods on
2351
-* ``throw(type, value=None, traceback=None)`` is used to raise an exception
2352
- inside the generator; the exception is raised by the ``yield`` expression
2353
- where the generator's execution is paused.
2354
+* :meth:`throw(type, value=None, traceback=None) <generator.throw>` is used to
2355
+ raise an exception inside the generator; the exception is raised by the
2356
+ ``yield`` expression where the generator's execution is paused.
2358
-* ``close()`` raises a :exc:`GeneratorExit` exception inside the generator to
2359
- terminate the iteration. On receiving this exception, the generator's code
2360
- must either raise :exc:`GeneratorExit` or :exc:`StopIteration`; catching the
2361
- exception and doing anything else is illegal and will trigger a
2362
- :exc:`RuntimeError`. ``close()`` will also be called by Python's garbage
2363
- collector when the generator is garbage-collected.
2364
+* :meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the
2365
+ generator to terminate the iteration. On receiving this exception, the
2366
+ generator's code must either raise :exc:`GeneratorExit` or
2367
+ :exc:`StopIteration`; catching the exception and doing anything else is
2368
+ illegal and will trigger a :exc:`RuntimeError`. :meth:`~generator.close`
2369
+ will also be called by Python's garbage collector when the generator is
2370
+ garbage-collected.
2372
If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
2373
using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
2374
@@ -624,13 +621,12 @@
2375
Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the
2376
features of generator expressions:
2378
-``map(f, iterA, iterB, ...)`` returns an iterator over the sequence
2379
+:func:`map(f, iterA, iterB, ...) <map>` returns an iterator over the sequence
2380
``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
2383
... return s.upper()
2386
>>> list(map(upper, ['sentence', 'fragment']))
2387
['SENTENCE', 'FRAGMENT']
2388
>>> [upper(s) for s in ['sentence', 'fragment']]
2389
@@ -638,11 +634,11 @@
2391
You can of course achieve the same effect with a list comprehension.
2393
-``filter(predicate, iter)`` returns an iterator over all the sequence elements
2394
-that meet a certain condition, and is similarly duplicated by list
2395
-comprehensions. A **predicate** is a function that returns the truth value of
2396
-some condition; for use with :func:`filter`, the predicate must take a single
2398
+:func:`filter(predicate, iter) <filter>` returns an iterator over all the
2399
+sequence elements that meet a certain condition, and is similarly duplicated by
2400
+list comprehensions. A **predicate** is a function that returns the truth
2401
+value of some condition; for use with :func:`filter`, the predicate must take a
2405
... return (x % 2) == 0
2410
-``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples
2411
-containing the count and each element. ::
2412
+:func:`enumerate(iter) <enumerate>` counts off the elements in the iterable,
2413
+returning 2-tuples containing the count and each element. ::
2415
>>> for item in enumerate(['subject', 'verb', 'object']):
2417
@@ -674,29 +670,28 @@
2418
if line.strip() == '':
2419
print('Blank line at line #%i' % i)
2421
-``sorted(iterable, [key=None], [reverse=False])`` collects all the elements of
2422
-the iterable into a list, sorts the list, and returns the sorted result. The
2423
-``key``, and ``reverse`` arguments are passed through to the constructed list's
2424
-``.sort()`` method. ::
2425
+:func:`sorted(iterable, key=None, reverse=False) <sorted>` collects all the
2426
+elements of the iterable into a list, sorts the list, and returns the sorted
2427
+result. The *key*, and *reverse* arguments are passed through to the
2428
+constructed list's :meth:`~list.sort` method. ::
2431
>>> # Generate 8 random numbers between [0, 10000)
2432
>>> rand_list = random.sample(range(10000), 8)
2434
+ >>> rand_list #doctest: +SKIP
2435
[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
2436
- >>> sorted(rand_list)
2437
+ >>> sorted(rand_list) #doctest: +SKIP
2438
[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
2439
- >>> sorted(rand_list, reverse=True)
2440
+ >>> sorted(rand_list, reverse=True) #doctest: +SKIP
2441
[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
2443
-(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the
2444
-Python wiki at http://wiki.python.org/moin/HowTo/Sorting.)
2445
+(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)
2448
-The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an
2449
-iterable's contents. :func:`any` returns True if any element in the iterable is
2450
-a true value, and :func:`all` returns True if all of the elements are true
2452
+The :func:`any(iter) <any>` and :func:`all(iter) <all>` built-ins look at the
2453
+truth values of an iterable's contents. :func:`any` returns True if any element
2454
+in the iterable is a true value, and :func:`all` returns True if all of the
2455
+elements are true values:
2463
-``zip(iterA, iterB, ...)`` takes one element from each iterable and
2464
+:func:`zip(iterA, iterB, ...) <zip>` takes one element from each iterable and
2465
returns them in a tuple::
2467
zip(['a', 'b', 'c'], (1, 2, 3)) =>
2468
@@ -752,42 +747,44 @@
2469
Creating new iterators
2470
----------------------
2472
-``itertools.count(n)`` returns an infinite stream of integers, increasing by 1
2473
-each time. You can optionally supply the starting number, which defaults to 0::
2474
+:func:`itertools.count(n) <itertools.count>` returns an infinite stream of
2475
+integers, increasing by 1 each time. You can optionally supply the starting
2476
+number, which defaults to 0::
2478
itertools.count() =>
2479
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
2480
itertools.count(10) =>
2481
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
2483
-``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable
2484
-and returns a new iterator that returns its elements from first to last. The
2485
-new iterator will repeat these elements infinitely. ::
2486
+:func:`itertools.cycle(iter) <itertools.cycle>` saves a copy of the contents of
2487
+a provided iterable and returns a new iterator that returns its elements from
2488
+first to last. The new iterator will repeat these elements infinitely. ::
2490
itertools.cycle([1,2,3,4,5]) =>
2491
1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
2493
-``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or
2494
-returns the element endlessly if ``n`` is not provided. ::
2495
+:func:`itertools.repeat(elem, [n]) <itertools.repeat>` returns the provided
2496
+element *n* times, or returns the element endlessly if *n* is not provided. ::
2498
itertools.repeat('abc') =>
2499
abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
2500
itertools.repeat('abc', 5) =>
2501
abc, abc, abc, abc, abc
2503
-``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as
2504
-input, and returns all the elements of the first iterator, then all the elements
2505
-of the second, and so on, until all of the iterables have been exhausted. ::
2506
+:func:`itertools.chain(iterA, iterB, ...) <itertools.chain>` takes an arbitrary
2507
+number of iterables as input, and returns all the elements of the first
2508
+iterator, then all the elements of the second, and so on, until all of the
2509
+iterables have been exhausted. ::
2511
itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
2514
-``itertools.islice(iter, [start], stop, [step])`` returns a stream that's a
2515
-slice of the iterator. With a single ``stop`` argument, it will return the
2516
-first ``stop`` elements. If you supply a starting index, you'll get
2517
-``stop-start`` elements, and if you supply a value for ``step``, elements will
2518
-be skipped accordingly. Unlike Python's string and list slicing, you can't use
2519
-negative values for ``start``, ``stop``, or ``step``. ::
2520
+:func:`itertools.islice(iter, [start], stop, [step]) <itertools.islice>` returns
2521
+a stream that's a slice of the iterator. With a single *stop* argument, it
2522
+will return the first *stop* elements. If you supply a starting index, you'll
2523
+get *stop-start* elements, and if you supply a value for *step*, elements
2524
+will be skipped accordingly. Unlike Python's string and list slicing, you can't
2525
+use negative values for *start*, *stop*, or *step*. ::
2527
itertools.islice(range(10), 8) =>
2528
0, 1, 2, 3, 4, 5, 6, 7
2529
@@ -796,9 +793,10 @@
2530
itertools.islice(range(10), 2, 8, 2) =>
2533
-``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n``
2534
-independent iterators that will all return the contents of the source iterator.
2535
-If you don't supply a value for ``n``, the default is 2. Replicating iterators
2536
+:func:`itertools.tee(iter, [n]) <itertools.tee>` replicates an iterator; it
2537
+returns *n* independent iterators that will all return the contents of the
2539
+If you don't supply a value for *n*, the default is 2. Replicating iterators
2540
requires saving some of the contents of the source iterator, so this can consume
2541
significant memory if the iterator is large and one of the new iterators is
2542
consumed more than the others. ::
2543
@@ -816,19 +814,21 @@
2544
Calling functions on elements
2545
-----------------------------
2547
-The ``operator`` module contains a set of functions corresponding to Python's
2548
-operators. Some examples are ``operator.add(a, b)`` (adds two values),
2549
-``operator.ne(a, b)`` (same as ``a!=b``), and ``operator.attrgetter('id')``
2550
-(returns a callable that fetches the ``"id"`` attribute).
2551
+The :mod:`operator` module contains a set of functions corresponding to Python's
2552
+operators. Some examples are :func:`operator.add(a, b) <operator.add>` (adds
2553
+two values), :func:`operator.ne(a, b) <operator.ne>` (same as ``a != b``), and
2554
+:func:`operator.attrgetter('id') <operator.attrgetter>`
2555
+(returns a callable that fetches the ``.id`` attribute).
2557
-``itertools.starmap(func, iter)`` assumes that the iterable will return a stream
2558
-of tuples, and calls ``f()`` using these tuples as the arguments::
2559
+:func:`itertools.starmap(func, iter) <itertools.starmap>` assumes that the
2560
+iterable will return a stream of tuples, and calls *func* using these tuples as
2563
itertools.starmap(os.path.join,
2564
- [('/usr', 'bin', 'java'), ('/bin', 'python'),
2565
- ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])
2566
+ [('/bin', 'python'), ('/usr', 'bin', 'java'),
2567
+ ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
2569
- /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby
2570
+ /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
2574
@@ -837,20 +837,18 @@
2575
Another group of functions chooses a subset of an iterator's elements based on a
2578
-``itertools.filterfalse(predicate, iter)`` is the opposite, returning all
2579
-elements for which the predicate returns false::
2580
+:func:`itertools.filterfalse(predicate, iter) <itertools.filterfalse>` is the
2581
+opposite, returning all elements for which the predicate returns false::
2583
itertools.filterfalse(is_even, itertools.count()) =>
2584
1, 3, 5, 7, 9, 11, 13, 15, ...
2586
-``itertools.takewhile(predicate, iter)`` returns elements for as long as the
2587
-predicate returns true. Once the predicate returns false, the iterator will
2588
-signal the end of its results.
2591
+:func:`itertools.takewhile(predicate, iter) <itertools.takewhile>` returns
2592
+elements for as long as the predicate returns true. Once the predicate returns
2593
+false, the iterator will signal the end of its results. ::
2595
def less_than_10(x):
2599
itertools.takewhile(less_than_10, itertools.count()) =>
2600
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2601
@@ -858,10 +856,9 @@
2602
itertools.takewhile(is_even, itertools.count()) =>
2605
-``itertools.dropwhile(predicate, iter)`` discards elements while the predicate
2606
-returns true, and then returns the rest of the iterable's results.
2609
+:func:`itertools.dropwhile(predicate, iter) <itertools.dropwhile>` discards
2610
+elements while the predicate returns true, and then returns the rest of the
2611
+iterable's results. ::
2613
itertools.dropwhile(less_than_10, itertools.count()) =>
2614
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
2615
@@ -873,14 +870,14 @@
2619
-The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is
2620
-the most complicated. ``key_func(elem)`` is a function that can compute a key
2621
-value for each element returned by the iterable. If you don't supply a key
2622
-function, the key is simply each element itself.
2623
+The last function I'll discuss, :func:`itertools.groupby(iter, key_func=None)
2624
+<itertools.groupby>`, is the most complicated. ``key_func(elem)`` is a function
2625
+that can compute a key value for each element returned by the iterable. If you
2626
+don't supply a key function, the key is simply each element itself.
2628
-``groupby()`` collects all the consecutive elements from the underlying iterable
2629
-that have the same key value, and returns a stream of 2-tuples containing a key
2630
-value and an iterator for the elements with that key.
2631
+:func:`~itertools.groupby` collects all the consecutive elements from the
2632
+underlying iterable that have the same key value, and returns a stream of
2633
+2-tuples containing a key value and an iterator for the elements with that key.
2641
- def get_state (city_state):
2642
+ def get_state(city_state):
2643
return city_state[1]
2645
itertools.groupby(city_list, get_state) =>
2648
('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
2650
-``groupby()`` assumes that the underlying iterable's contents will already be
2651
-sorted based on the key. Note that the returned iterators also use the
2652
-underlying iterable, so you have to consume the results of iterator-1 before
2653
+:func:`~itertools.groupby` assumes that the underlying iterable's contents will
2654
+already be sorted based on the key. Note that the returned iterators also use
2655
+the underlying iterable, so you have to consume the results of iterator-1 before
2656
requesting iterator-2 and its corresponding key.
2659
@@ -926,33 +923,34 @@
2660
``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
2661
one of ``f()``'s parameters. This is called "partial function application".
2663
-The constructor for ``partial`` takes the arguments ``(function, arg1, arg2,
2664
-... kwarg1=value1, kwarg2=value2)``. The resulting object is callable, so you
2665
-can just call it to invoke ``function`` with the filled-in arguments.
2666
+The constructor for :func:`~functools.partial` takes the arguments
2667
+``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``. The resulting
2668
+object is callable, so you can just call it to invoke ``function`` with the
2669
+filled-in arguments.
2671
Here's a small but realistic example::
2675
- def log (message, subsystem):
2676
- "Write the contents of 'message' to the specified subsystem."
2677
+ def log(message, subsystem):
2678
+ """Write the contents of 'message' to the specified subsystem."""
2679
print('%s: %s' % (subsystem, message))
2682
server_log = functools.partial(log, subsystem='server')
2683
server_log('Unable to open socket')
2685
-``functools.reduce(func, iter, [initial_value])`` cumulatively performs an
2686
-operation on all the iterable's elements and, therefore, can't be applied to
2687
-infinite iterables. (Note it is not in :mod:`builtins`, but in the
2688
-:mod:`functools` module.) ``func`` must be a function that takes two elements
2689
-and returns a single value. :func:`functools.reduce` takes the first two
2690
-elements A and B returned by the iterator and calculates ``func(A, B)``. It
2691
-then requests the third element, C, calculates ``func(func(A, B), C)``, combines
2692
-this result with the fourth element returned, and continues until the iterable
2693
-is exhausted. If the iterable returns no values at all, a :exc:`TypeError`
2694
-exception is raised. If the initial value is supplied, it's used as a starting
2695
-point and ``func(initial_value, A)`` is the first calculation. ::
2696
+:func:`functools.reduce(func, iter, [initial_value]) <functools.reduce>`
2697
+cumulatively performs an operation on all the iterable's elements and,
2698
+therefore, can't be applied to infinite iterables. *func* must be a function
2699
+that takes two elements and returns a single value. :func:`functools.reduce`
2700
+takes the first two elements A and B returned by the iterator and calculates
2701
+``func(A, B)``. It then requests the third element, C, calculates
2702
+``func(func(A, B), C)``, combines this result with the fourth element returned,
2703
+and continues until the iterable is exhausted. If the iterable returns no
2704
+values at all, a :exc:`TypeError` exception is raised. If the initial value is
2705
+supplied, it's used as a starting point and ``func(initial_value, A)`` is the
2706
+first calculation. ::
2708
>>> import operator, functools
2709
>>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
2714
-For many uses of :func:`functools.reduce`, though, it can be clearer to just write the
2715
-obvious :keyword:`for` loop::
2716
+For many uses of :func:`functools.reduce`, though, it can be clearer to just
2717
+write the obvious :keyword:`for` loop::
2721
@@ -1023,28 +1021,23 @@
2722
existing_files = filter(os.path.exists, file_list)
2724
If the function you need doesn't exist, you need to write it. One way to write
2725
-small functions is to use the ``lambda`` statement. ``lambda`` takes a number
2726
-of parameters and an expression combining these parameters, and creates a small
2727
-function that returns the value of the expression::
2728
+small functions is to use the :keyword:`lambda` statement. ``lambda`` takes a
2729
+number of parameters and an expression combining these parameters, and creates
2730
+an anonymous function that returns the value of the expression::
2732
- lowercase = lambda x: x.lower()
2733
+ adder = lambda x, y: x+y
2735
print_assign = lambda name, value: name + '=' + str(value)
2737
- adder = lambda x, y: x+y
2739
An alternative is to just use the ``def`` statement and define a function in the
2747
def print_assign(name, value):
2748
return name + '=' + str(value)
2753
Which alternative is preferable? That's a style question; my usual course is to
2754
avoid using ``lambda``.
2756
@@ -1053,9 +1046,7 @@
2757
expression, which means you can't have multiway ``if... elif... else``
2758
comparisons or ``try... except`` statements. If you try to do too much in a
2759
``lambda`` statement, you'll end up with an overly complicated expression that's
2760
-hard to read. Quick, what's the following code doing?
2763
+hard to read. Quick, what's the following code doing? ::
2766
total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
2767
@@ -1065,7 +1056,7 @@
2771
- def combine (a, b):
2772
+ def combine(a, b):
2773
return 0, a[1] + b[1]
2775
total = functools.reduce(combine, items)[1]
2776
@@ -1085,12 +1076,12 @@
2777
Fredrik Lundh once suggested the following set of rules for refactoring uses of
2780
-1) Write a lambda function.
2781
-2) Write a comment explaining what the heck that lambda does.
2782
-3) Study the comment for a while, and think of a name that captures the essence
2783
+1. Write a lambda function.
2784
+2. Write a comment explaining what the heck that lambda does.
2785
+3. Study the comment for a while, and think of a name that captures the essence
2787
-4) Convert the lambda to a def statement, using that name.
2788
-5) Remove the comment.
2789
+4. Convert the lambda to a def statement, using that name.
2790
+5. Remove the comment.
2792
I really like these rules, but you're free to disagree
2793
about whether this lambda-free style is better.
2069
2794
diff -r 3d0686d90f55 Doc/howto/index.rst
2070
2795
--- a/Doc/howto/index.rst
2071
2796
+++ b/Doc/howto/index.rst
6016
7262
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
6018
7264
c.execute('insert into stocks values (?,?,?,?,?)', t)
6020
calling the cursor method, then calls the cursor's :meth:`executemany
6021
<Cursor.executemany>` method with the parameters given.
6024
.. method:: Connection.executescript(sql_script)
6026
This is a nonstandard shortcut that creates an intermediate cursor object by
6027
@@ -376,22 +376,22 @@
6028
aggregates or whole new virtual table implementations. One well-known
6029
extension is the fulltext-search extension distributed with SQLite.
6031
+ Loadable extensions are disabled by default. See [#f1]_.
6033
.. versionadded:: 3.2
6035
.. literalinclude:: ../includes/sqlite3/load_extension.py
6037
- Loadable extensions are disabled by default. See [#f1]_.
6039
.. method:: Connection.load_extension(path)
6041
This routine loads a SQLite extension from a shared library. You have to
6042
enable extension loading with :meth:`enable_load_extension` before you can
6045
+ Loadable extensions are disabled by default. See [#f1]_.
6047
.. versionadded:: 3.2
6049
- Loadable extensions are disabled by default. See [#f1]_.
6051
.. attribute:: Connection.row_factory
6053
You can change this attribute to a callable that accepts the cursor and the
6055
or :const:`None` when no more data is available.
7265
@@ -221,239 +222,238 @@
7267
A SQLite database connection has the following attributes and methods:
7269
-.. attribute:: Connection.isolation_level
7270
+ .. attribute:: isolation_level
7272
- Get or set the current isolation level. :const:`None` for autocommit mode or
7273
- one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
7274
- :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
7275
+ Get or set the current isolation level. :const:`None` for autocommit mode or
7276
+ one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
7277
+ :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
7279
-.. attribute:: Connection.in_transaction
7280
+ .. attribute:: in_transaction
7282
- :const:`True` if a transaction is active (there are uncommitted changes),
7283
- :const:`False` otherwise. Read-only attribute.
7284
+ :const:`True` if a transaction is active (there are uncommitted changes),
7285
+ :const:`False` otherwise. Read-only attribute.
7287
- .. versionadded:: 3.2
7288
+ .. versionadded:: 3.2
7290
-.. method:: Connection.cursor([cursorClass])
7291
+ .. method:: cursor([cursorClass])
7293
- The cursor method accepts a single optional parameter *cursorClass*. If
7294
- supplied, this must be a custom cursor class that extends
7295
- :class:`sqlite3.Cursor`.
7296
+ The cursor method accepts a single optional parameter *cursorClass*. If
7297
+ supplied, this must be a custom cursor class that extends
7298
+ :class:`sqlite3.Cursor`.
7300
-.. method:: Connection.commit()
7301
+ .. method:: commit()
7303
- This method commits the current transaction. If you don't call this method,
7304
- anything you did since the last call to ``commit()`` is not visible from
7305
- other database connections. If you wonder why you don't see the data you've
7306
- written to the database, please check you didn't forget to call this method.
7307
+ This method commits the current transaction. If you don't call this method,
7308
+ anything you did since the last call to ``commit()`` is not visible from
7309
+ other database connections. If you wonder why you don't see the data you've
7310
+ written to the database, please check you didn't forget to call this method.
7312
-.. method:: Connection.rollback()
7313
+ .. method:: rollback()
7315
- This method rolls back any changes to the database since the last call to
7317
+ This method rolls back any changes to the database since the last call to
7320
-.. method:: Connection.close()
7321
+ .. method:: close()
7323
- This closes the database connection. Note that this does not automatically
7324
- call :meth:`commit`. If you just close your database connection without
7325
- calling :meth:`commit` first, your changes will be lost!
7326
+ This closes the database connection. Note that this does not automatically
7327
+ call :meth:`commit`. If you just close your database connection without
7328
+ calling :meth:`commit` first, your changes will be lost!
7330
-.. method:: Connection.execute(sql, [parameters])
7331
+ .. method:: execute(sql, [parameters])
7333
- This is a nonstandard shortcut that creates an intermediate cursor object by
7334
- calling the cursor method, then calls the cursor's :meth:`execute
7335
- <Cursor.execute>` method with the parameters given.
7336
+ This is a nonstandard shortcut that creates an intermediate cursor object by
7337
+ calling the cursor method, then calls the cursor's :meth:`execute
7338
+ <Cursor.execute>` method with the parameters given.
7341
-.. method:: Connection.executemany(sql, [parameters])
7342
+ .. method:: executemany(sql, [parameters])
7344
- This is a nonstandard shortcut that creates an intermediate cursor object by
7345
- calling the cursor method, then calls the cursor's :meth:`executemany
7346
- <Cursor.executemany>` method with the parameters given.
7347
+ This is a nonstandard shortcut that creates an intermediate cursor object by
7348
+ calling the cursor method, then calls the cursor's :meth:`executemany
7349
+ <Cursor.executemany>` method with the parameters given.
7351
+ .. method:: executescript(sql_script)
7353
-.. method:: Connection.executescript(sql_script)
7354
+ This is a nonstandard shortcut that creates an intermediate cursor object by
7355
+ calling the cursor method, then calls the cursor's :meth:`executescript
7356
+ <Cursor.executescript>` method with the parameters given.
7358
- This is a nonstandard shortcut that creates an intermediate cursor object by
7359
- calling the cursor method, then calls the cursor's :meth:`executescript
7360
- <Cursor.executescript>` method with the parameters given.
7362
+ .. method:: create_function(name, num_params, func)
7364
-.. method:: Connection.create_function(name, num_params, func)
7365
+ Creates a user-defined function that you can later use from within SQL
7366
+ statements under the function name *name*. *num_params* is the number of
7367
+ parameters the function accepts, and *func* is a Python callable that is called
7368
+ as the SQL function.
7370
- Creates a user-defined function that you can later use from within SQL
7371
- statements under the function name *name*. *num_params* is the number of
7372
- parameters the function accepts, and *func* is a Python callable that is called
7373
- as the SQL function.
7374
+ The function can return any of the types supported by SQLite: bytes, str, int,
7377
- The function can return any of the types supported by SQLite: bytes, str, int,
7382
+ .. literalinclude:: ../includes/sqlite3/md5func.py
7384
- .. literalinclude:: ../includes/sqlite3/md5func.py
7386
+ .. method:: create_aggregate(name, num_params, aggregate_class)
7388
-.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
7389
+ Creates a user-defined aggregate function.
7391
- Creates a user-defined aggregate function.
7392
+ The aggregate class must implement a ``step`` method, which accepts the number
7393
+ of parameters *num_params*, and a ``finalize`` method which will return the
7394
+ final result of the aggregate.
7396
- The aggregate class must implement a ``step`` method, which accepts the number
7397
- of parameters *num_params*, and a ``finalize`` method which will return the
7398
- final result of the aggregate.
7399
+ The ``finalize`` method can return any of the types supported by SQLite:
7400
+ bytes, str, int, float and None.
7402
- The ``finalize`` method can return any of the types supported by SQLite:
7403
- bytes, str, int, float and None.
7407
+ .. literalinclude:: ../includes/sqlite3/mysumaggr.py
7409
- .. literalinclude:: ../includes/sqlite3/mysumaggr.py
7411
+ .. method:: create_collation(name, callable)
7413
-.. method:: Connection.create_collation(name, callable)
7414
+ Creates a collation with the specified *name* and *callable*. The callable will
7415
+ be passed two string arguments. It should return -1 if the first is ordered
7416
+ lower than the second, 0 if they are ordered equal and 1 if the first is ordered
7417
+ higher than the second. Note that this controls sorting (ORDER BY in SQL) so
7418
+ your comparisons don't affect other SQL operations.
7420
- Creates a collation with the specified *name* and *callable*. The callable will
7421
- be passed two string arguments. It should return -1 if the first is ordered
7422
- lower than the second, 0 if they are ordered equal and 1 if the first is ordered
7423
- higher than the second. Note that this controls sorting (ORDER BY in SQL) so
7424
- your comparisons don't affect other SQL operations.
7425
+ Note that the callable will get its parameters as Python bytestrings, which will
7426
+ normally be encoded in UTF-8.
7428
- Note that the callable will get its parameters as Python bytestrings, which will
7429
- normally be encoded in UTF-8.
7430
+ The following example shows a custom collation that sorts "the wrong way":
7432
- The following example shows a custom collation that sorts "the wrong way":
7433
+ .. literalinclude:: ../includes/sqlite3/collation_reverse.py
7435
- .. literalinclude:: ../includes/sqlite3/collation_reverse.py
7436
+ To remove a collation, call ``create_collation`` with None as callable::
7438
- To remove a collation, call ``create_collation`` with None as callable::
7439
+ con.create_collation("reverse", None)
7441
- con.create_collation("reverse", None)
7443
+ .. method:: interrupt()
7445
-.. method:: Connection.interrupt()
7446
+ You can call this method from a different thread to abort any queries that might
7447
+ be executing on the connection. The query will then abort and the caller will
7450
- You can call this method from a different thread to abort any queries that might
7451
- be executing on the connection. The query will then abort and the caller will
7454
+ .. method:: set_authorizer(authorizer_callback)
7456
-.. method:: Connection.set_authorizer(authorizer_callback)
7457
+ This routine registers a callback. The callback is invoked for each attempt to
7458
+ access a column of a table in the database. The callback should return
7459
+ :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
7460
+ statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
7461
+ column should be treated as a NULL value. These constants are available in the
7462
+ :mod:`sqlite3` module.
7464
- This routine registers a callback. The callback is invoked for each attempt to
7465
- access a column of a table in the database. The callback should return
7466
- :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
7467
- statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
7468
- column should be treated as a NULL value. These constants are available in the
7469
- :mod:`sqlite3` module.
7470
+ The first argument to the callback signifies what kind of operation is to be
7471
+ authorized. The second and third argument will be arguments or :const:`None`
7472
+ depending on the first argument. The 4th argument is the name of the database
7473
+ ("main", "temp", etc.) if applicable. The 5th argument is the name of the
7474
+ inner-most trigger or view that is responsible for the access attempt or
7475
+ :const:`None` if this access attempt is directly from input SQL code.
7477
- The first argument to the callback signifies what kind of operation is to be
7478
- authorized. The second and third argument will be arguments or :const:`None`
7479
- depending on the first argument. The 4th argument is the name of the database
7480
- ("main", "temp", etc.) if applicable. The 5th argument is the name of the
7481
- inner-most trigger or view that is responsible for the access attempt or
7482
- :const:`None` if this access attempt is directly from input SQL code.
7483
+ Please consult the SQLite documentation about the possible values for the first
7484
+ argument and the meaning of the second and third argument depending on the first
7485
+ one. All necessary constants are available in the :mod:`sqlite3` module.
7487
- Please consult the SQLite documentation about the possible values for the first
7488
- argument and the meaning of the second and third argument depending on the first
7489
- one. All necessary constants are available in the :mod:`sqlite3` module.
7491
+ .. method:: set_progress_handler(handler, n)
7493
-.. method:: Connection.set_progress_handler(handler, n)
7494
+ This routine registers a callback. The callback is invoked for every *n*
7495
+ instructions of the SQLite virtual machine. This is useful if you want to
7496
+ get called from SQLite during long-running operations, for example to update
7499
- This routine registers a callback. The callback is invoked for every *n*
7500
- instructions of the SQLite virtual machine. This is useful if you want to
7501
- get called from SQLite during long-running operations, for example to update
7503
+ If you want to clear any previously installed progress handler, call the
7504
+ method with :const:`None` for *handler*.
7506
- If you want to clear any previously installed progress handler, call the
7507
- method with :const:`None` for *handler*.
7509
+ .. method:: enable_load_extension(enabled)
7511
-.. method:: Connection.enable_load_extension(enabled)
7512
+ This routine allows/disallows the SQLite engine to load SQLite extensions
7513
+ from shared libraries. SQLite extensions can define new functions,
7514
+ aggregates or whole new virtual table implementations. One well-known
7515
+ extension is the fulltext-search extension distributed with SQLite.
7517
- This routine allows/disallows the SQLite engine to load SQLite extensions
7518
- from shared libraries. SQLite extensions can define new functions,
7519
- aggregates or whole new virtual table implementations. One well-known
7520
- extension is the fulltext-search extension distributed with SQLite.
7521
+ Loadable extensions are disabled by default. See [#f1]_.
7523
- .. versionadded:: 3.2
7524
+ .. versionadded:: 3.2
7526
- .. literalinclude:: ../includes/sqlite3/load_extension.py
7527
+ .. literalinclude:: ../includes/sqlite3/load_extension.py
7529
- Loadable extensions are disabled by default. See [#f1]_.
7530
+ .. method:: load_extension(path)
7532
-.. method:: Connection.load_extension(path)
7533
+ This routine loads a SQLite extension from a shared library. You have to
7534
+ enable extension loading with :meth:`enable_load_extension` before you can
7537
- This routine loads a SQLite extension from a shared library. You have to
7538
- enable extension loading with :meth:`enable_load_extension` before you can
7540
+ Loadable extensions are disabled by default. See [#f1]_.
7542
- .. versionadded:: 3.2
7543
+ .. versionadded:: 3.2
7545
- Loadable extensions are disabled by default. See [#f1]_.
7546
+ .. attribute:: row_factory
7548
-.. attribute:: Connection.row_factory
7549
+ You can change this attribute to a callable that accepts the cursor and the
7550
+ original row as a tuple and will return the real result row. This way, you can
7551
+ implement more advanced ways of returning results, such as returning an object
7552
+ that can also access columns by name.
7554
- You can change this attribute to a callable that accepts the cursor and the
7555
- original row as a tuple and will return the real result row. This way, you can
7556
- implement more advanced ways of returning results, such as returning an object
7557
- that can also access columns by name.
7561
+ .. literalinclude:: ../includes/sqlite3/row_factory.py
7563
- .. literalinclude:: ../includes/sqlite3/row_factory.py
7564
+ If returning a tuple doesn't suffice and you want name-based access to
7565
+ columns, you should consider setting :attr:`row_factory` to the
7566
+ highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
7567
+ index-based and case-insensitive name-based access to columns with almost no
7568
+ memory overhead. It will probably be better than your own custom
7569
+ dictionary-based approach or even a db_row based solution.
7571
- If returning a tuple doesn't suffice and you want name-based access to
7572
- columns, you should consider setting :attr:`row_factory` to the
7573
- highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
7574
- index-based and case-insensitive name-based access to columns with almost no
7575
- memory overhead. It will probably be better than your own custom
7576
- dictionary-based approach or even a db_row based solution.
7577
+ .. XXX what's a db_row-based solution?
7579
- .. XXX what's a db_row-based solution?
7581
+ .. attribute:: text_factory
7583
-.. attribute:: Connection.text_factory
7584
+ Using this attribute you can control what objects are returned for the ``TEXT``
7585
+ data type. By default, this attribute is set to :class:`str` and the
7586
+ :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
7587
+ return bytestrings instead, you can set it to :class:`bytes`.
7589
- Using this attribute you can control what objects are returned for the ``TEXT``
7590
- data type. By default, this attribute is set to :class:`str` and the
7591
- :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
7592
- return bytestrings instead, you can set it to :class:`bytes`.
7593
+ For efficiency reasons, there's also a way to return :class:`str` objects
7594
+ only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
7595
+ this attribute to :const:`sqlite3.OptimizedUnicode`.
7597
- For efficiency reasons, there's also a way to return :class:`str` objects
7598
- only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
7599
- this attribute to :const:`sqlite3.OptimizedUnicode`.
7600
+ You can also set it to any other callable that accepts a single bytestring
7601
+ parameter and returns the resulting object.
7603
- You can also set it to any other callable that accepts a single bytestring
7604
- parameter and returns the resulting object.
7605
+ See the following example code for illustration:
7607
- See the following example code for illustration:
7608
+ .. literalinclude:: ../includes/sqlite3/text_factory.py
7610
- .. literalinclude:: ../includes/sqlite3/text_factory.py
7612
+ .. attribute:: total_changes
7614
-.. attribute:: Connection.total_changes
7615
+ Returns the total number of database rows that have been modified, inserted, or
7616
+ deleted since the database connection was opened.
7618
- Returns the total number of database rows that have been modified, inserted, or
7619
- deleted since the database connection was opened.
7621
+ .. attribute:: iterdump
7623
-.. attribute:: Connection.iterdump
7624
+ Returns an iterator to dump the database in an SQL text format. Useful when
7625
+ saving an in-memory database for later restoration. This function provides
7626
+ the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
7629
- Returns an iterator to dump the database in an SQL text format. Useful when
7630
- saving an in-memory database for later restoration. This function provides
7631
- the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
7636
+ # Convert file existing_db.db to SQL dump file dump.sql
7637
+ import sqlite3, os
7639
- # Convert file existing_db.db to SQL dump file dump.sql
7640
- import sqlite3, os
7642
- con = sqlite3.connect('existing_db.db')
7643
- with open('dump.sql', 'w') as f:
7644
- for line in con.iterdump():
7645
- f.write('%s\n' % line)
7646
+ con = sqlite3.connect('existing_db.db')
7647
+ with open('dump.sql', 'w') as f:
7648
+ for line in con.iterdump():
7649
+ f.write('%s\n' % line)
7652
.. _sqlite3-cursor-objects:
7653
@@ -465,110 +465,110 @@
7655
A :class:`Cursor` instance has the following attributes and methods.
7657
-.. method:: Cursor.execute(sql, [parameters])
7658
+ .. method:: execute(sql, [parameters])
7660
- Executes an SQL statement. The SQL statement may be parametrized (i. e.
7661
- placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
7662
- kinds of placeholders: question marks (qmark style) and named placeholders
7664
+ Executes an SQL statement. The SQL statement may be parametrized (i. e.
7665
+ placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
7666
+ kinds of placeholders: question marks (qmark style) and named placeholders
7669
- Here's an example of both styles:
7670
+ Here's an example of both styles:
7672
- .. literalinclude:: ../includes/sqlite3/execute_1.py
7673
+ .. literalinclude:: ../includes/sqlite3/execute_1.py
7675
- :meth:`execute` will only execute a single SQL statement. If you try to execute
7676
- more than one statement with it, it will raise a Warning. Use
7677
- :meth:`executescript` if you want to execute multiple SQL statements with one
7679
+ :meth:`execute` will only execute a single SQL statement. If you try to execute
7680
+ more than one statement with it, it will raise a Warning. Use
7681
+ :meth:`executescript` if you want to execute multiple SQL statements with one
7685
-.. method:: Cursor.executemany(sql, seq_of_parameters)
7686
+ .. method:: executemany(sql, seq_of_parameters)
7688
- Executes an SQL command against all parameter sequences or mappings found in
7689
- the sequence *sql*. The :mod:`sqlite3` module also allows using an
7690
- :term:`iterator` yielding parameters instead of a sequence.
7691
+ Executes an SQL command against all parameter sequences or mappings found in
7692
+ the sequence *sql*. The :mod:`sqlite3` module also allows using an
7693
+ :term:`iterator` yielding parameters instead of a sequence.
7695
- .. literalinclude:: ../includes/sqlite3/executemany_1.py
7696
+ .. literalinclude:: ../includes/sqlite3/executemany_1.py
7698
- Here's a shorter example using a :term:`generator`:
7699
+ Here's a shorter example using a :term:`generator`:
7701
- .. literalinclude:: ../includes/sqlite3/executemany_2.py
7702
+ .. literalinclude:: ../includes/sqlite3/executemany_2.py
7705
-.. method:: Cursor.executescript(sql_script)
7706
+ .. method:: executescript(sql_script)
7708
- This is a nonstandard convenience method for executing multiple SQL statements
7709
- at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
7710
- gets as a parameter.
7711
+ This is a nonstandard convenience method for executing multiple SQL statements
7712
+ at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
7713
+ gets as a parameter.
7715
- *sql_script* can be an instance of :class:`str` or :class:`bytes`.
7716
+ *sql_script* can be an instance of :class:`str` or :class:`bytes`.
7721
- .. literalinclude:: ../includes/sqlite3/executescript.py
7722
+ .. literalinclude:: ../includes/sqlite3/executescript.py
7725
-.. method:: Cursor.fetchone()
7726
+ .. method:: fetchone()
7728
- Fetches the next row of a query result set, returning a single sequence,
7729
- or :const:`None` when no more data is available.
7730
+ Fetches the next row of a query result set, returning a single sequence,
7731
+ or :const:`None` when no more data is available.
6058
7734
-.. method:: Cursor.fetchmany([size=cursor.arraysize])
6059
+.. method:: Cursor.fetchmany(size=cursor.arraysize)
6061
Fetches the next set of rows of a query result, returning a list. An empty
6062
list is returned when no more rows are available.
7735
+ .. method:: fetchmany(size=cursor.arraysize)
7737
- Fetches the next set of rows of a query result, returning a list. An empty
7738
- list is returned when no more rows are available.
7739
+ Fetches the next set of rows of a query result, returning a list. An empty
7740
+ list is returned when no more rows are available.
7742
- The number of rows to fetch per call is specified by the *size* parameter.
7743
- If it is not given, the cursor's arraysize determines the number of rows
7744
- to be fetched. The method should try to fetch as many rows as indicated by
7745
- the size parameter. If this is not possible due to the specified number of
7746
- rows not being available, fewer rows may be returned.
7747
+ The number of rows to fetch per call is specified by the *size* parameter.
7748
+ If it is not given, the cursor's arraysize determines the number of rows
7749
+ to be fetched. The method should try to fetch as many rows as indicated by
7750
+ the size parameter. If this is not possible due to the specified number of
7751
+ rows not being available, fewer rows may be returned.
7753
- Note there are performance considerations involved with the *size* parameter.
7754
- For optimal performance, it is usually best to use the arraysize attribute.
7755
- If the *size* parameter is used, then it is best for it to retain the same
7756
- value from one :meth:`fetchmany` call to the next.
7757
+ Note there are performance considerations involved with the *size* parameter.
7758
+ For optimal performance, it is usually best to use the arraysize attribute.
7759
+ If the *size* parameter is used, then it is best for it to retain the same
7760
+ value from one :meth:`fetchmany` call to the next.
7762
-.. method:: Cursor.fetchall()
7763
+ .. method:: fetchall()
7765
- Fetches all (remaining) rows of a query result, returning a list. Note that
7766
- the cursor's arraysize attribute can affect the performance of this operation.
7767
- An empty list is returned when no rows are available.
7768
+ Fetches all (remaining) rows of a query result, returning a list. Note that
7769
+ the cursor's arraysize attribute can affect the performance of this operation.
7770
+ An empty list is returned when no rows are available.
7773
-.. attribute:: Cursor.rowcount
7774
+ .. attribute:: rowcount
7776
- Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
7777
- attribute, the database engine's own support for the determination of "rows
7778
- affected"/"rows selected" is quirky.
7779
+ Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
7780
+ attribute, the database engine's own support for the determination of "rows
7781
+ affected"/"rows selected" is quirky.
7783
- For :meth:`executemany` statements, the number of modifications are summed up
7784
- into :attr:`rowcount`.
7785
+ For :meth:`executemany` statements, the number of modifications are summed up
7786
+ into :attr:`rowcount`.
7788
- As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
7789
- case no ``executeXX()`` has been performed on the cursor or the rowcount of the
7790
- last operation is not determinable by the interface". This includes ``SELECT``
7791
- statements because we cannot determine the number of rows a query produced
7792
- until all rows were fetched.
7793
+ As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
7794
+ case no ``executeXX()`` has been performed on the cursor or the rowcount of the
7795
+ last operation is not determinable by the interface". This includes ``SELECT``
7796
+ statements because we cannot determine the number of rows a query produced
7797
+ until all rows were fetched.
7799
- With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
7800
- you make a ``DELETE FROM table`` without any condition.
7801
+ With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
7802
+ you make a ``DELETE FROM table`` without any condition.
7804
-.. attribute:: Cursor.lastrowid
7805
+ .. attribute:: lastrowid
7807
- This read-only attribute provides the rowid of the last modified row. It is
7808
- only set if you issued a ``INSERT`` statement using the :meth:`execute`
7809
- method. For operations other than ``INSERT`` or when :meth:`executemany` is
7810
- called, :attr:`lastrowid` is set to :const:`None`.
7811
+ This read-only attribute provides the rowid of the last modified row. It is
7812
+ only set if you issued a ``INSERT`` statement using the :meth:`execute`
7813
+ method. For operations other than ``INSERT`` or when :meth:`executemany` is
7814
+ called, :attr:`lastrowid` is set to :const:`None`.
7816
-.. attribute:: Cursor.description
7817
+ .. attribute:: description
7819
- This read-only attribute provides the column names of the last query. To
7820
- remain compatible with the Python DB API, it returns a 7-tuple for each
7821
- column where the last six items of each tuple are :const:`None`.
7822
+ This read-only attribute provides the column names of the last query. To
7823
+ remain compatible with the Python DB API, it returns a 7-tuple for each
7824
+ column where the last six items of each tuple are :const:`None`.
7826
- It is set for ``SELECT`` statements without any matching rows as well.
7827
+ It is set for ``SELECT`` statements without any matching rows as well.
7829
.. _sqlite3-row-objects:
6063
7831
diff -r 3d0686d90f55 Doc/library/ssl.rst
6064
7832
--- a/Doc/library/ssl.rst
6065
7833
+++ b/Doc/library/ssl.rst
6329
@@ -408,18 +446,9 @@
8188
untrusted source makes a program vulnerable to `shell injection
8189
<http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
8190
a serious security flaw which can result in arbitrary command execution.
8191
- For this reason, the use of *shell=True* is **strongly discouraged** in cases
8192
- where the command string is constructed from external input::
8193
+ For this reason, the use of ``shell=True`` is **strongly discouraged**
8194
+ in cases where the command string is constructed from external input::
8196
>>> from subprocess import call
8197
>>> filename = input("What file would you like to display?\n")
8198
@@ -248,24 +286,27 @@
8202
-.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())
8203
+.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, \
8204
+ stderr=None, preexec_fn=None, close_fds=True, shell=False, \
8205
+ cwd=None, env=None, universal_newlines=False, \
8206
+ startupinfo=None, creationflags=0, restore_signals=True, \
8207
+ start_new_session=False, pass_fds=())
8210
+ Execute a child program in a new process. On Unix, the class uses
8211
+ :meth:`os.execvp`-like behavior to execute the child program. On Windows,
8212
+ the class uses the Windows ``CreateProcess()`` function. The arguments to
8213
+ :class:`Popen` are as follows.
8215
- *args* should be a string, or a sequence of program arguments. The program
8216
- to execute is normally the first item in the args sequence or the string if
8217
- a string is given, but can be explicitly set by using the *executable*
8218
- argument. When *executable* is given, the first item in the args sequence
8219
- is still treated by most programs as the command name, which can then be
8220
- different from the actual executable name. On Unix, it becomes the display
8221
- name for the executing program in utilities such as :program:`ps`.
8222
+ *args* should be a sequence of program arguments or else a single string.
8223
+ By default, the program to execute is the first item in *args* if *args* is
8224
+ a sequence. If *args* is a string, the interpretation is
8225
+ platform-dependent and described below. See the *shell* and *executable*
8226
+ arguments for additional differences from the default behavior. Unless
8227
+ otherwise stated, it is recommended to pass *args* as a sequence.
8229
- On Unix, with *shell=False* (default): In this case, the Popen class uses
8230
- :meth:`os.execvp` like behavior to execute the child program.
8231
- *args* should normally be a
8232
- sequence. If a string is specified for *args*, it will be used as the name
8233
- or path of the program to execute; this will only work if the program is
8234
- being given no arguments.
8235
+ On Unix, if *args* is a string, the string is interpreted as the name or
8236
+ path of the program to execute. However, this can only be done if not
8237
+ passing arguments to the program.
8241
@@ -286,27 +327,37 @@
8242
used in the shell (such as filenames containing spaces or the *echo* command
8243
shown above) are single list elements.
8245
- On Unix, with *shell=True*: If args is a string, it specifies the command
8246
- string to execute through the shell. This means that the string must be
8247
+ On Windows, if *args* is a sequence, it will be converted to a string in a
8248
+ manner described in :ref:`converting-argument-sequence`. This is because
8249
+ the underlying ``CreateProcess()`` operates on strings.
8251
+ The *shell* argument (which defaults to *False*) specifies whether to use
8252
+ the shell as the program to execute. If *shell* is *True*, it is
8253
+ recommended to pass *args* as a string rather than as a sequence.
8255
+ On Unix with ``shell=True``, the shell defaults to :file:`/bin/sh`. If
8256
+ *args* is a string, the string specifies the command
8257
+ to execute through the shell. This means that the string must be
8258
formatted exactly as it would be when typed at the shell prompt. This
8259
includes, for example, quoting or backslash escaping filenames with spaces in
8260
them. If *args* is a sequence, the first item specifies the command string, and
8261
any additional items will be treated as additional arguments to the shell
8262
- itself. That is to say, *Popen* does the equivalent of::
8263
+ itself. That is to say, :class:`Popen` does the equivalent of::
8265
Popen(['/bin/sh', '-c', args[0], args[1], ...])
8267
+ On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable
8268
+ specifies the default shell. The only time you need to specify
8269
+ ``shell=True`` on Windows is when the command you wish to execute is built
8270
+ into the shell (e.g. :command:`dir` or :command:`copy`). You do not need
8271
+ ``shell=True`` to run a batch file or console-based executable.
8275
- Enabling this option can be a security hazard if combined with untrusted
8276
- input. See the warning under :ref:`frequently-used-arguments`
8277
+ Passing ``shell=True`` can be a security hazard if combined with
8278
+ untrusted input. See the warning under :ref:`frequently-used-arguments`
8281
- On Windows: the :class:`Popen` class uses CreateProcess() to execute the
8282
- child program, which operates on strings. If *args* is a sequence, it will
8283
- be converted to a string in a manner described in
8284
- :ref:`converting-argument-sequence`.
8286
*bufsize*, if given, has the same meaning as the corresponding argument to the
8287
built-in open() function: :const:`0` means unbuffered, :const:`1` means line
8288
buffered, any other positive value means use a buffer of (approximately) that
8289
@@ -319,15 +370,15 @@
8290
enable buffering by setting *bufsize* to either -1 or a large enough
8291
positive value (such as 4096).
8293
- The *executable* argument specifies the program to execute. It is very seldom
8294
- needed: Usually, the program to execute is defined by the *args* argument. If
8295
- ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
8296
- the default shell is :file:`/bin/sh`. On Windows, the default shell is
8297
- specified by the :envvar:`COMSPEC` environment variable. The only reason you
8298
- would need to specify ``shell=True`` on Windows is where the command you
8299
- wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
8300
- You don't need ``shell=True`` to run a batch file, nor to run a console-based
8302
+ The *executable* argument specifies a replacement program to execute. It
8303
+ is very seldom needed. When ``shell=False``, *executable* replaces the
8304
+ program to execute specified by *args*. However, the original *args* is
8305
+ still passed to the program. Most programs treat the program specified
8306
+ by *args* as the command name, which can then be different from the program
8307
+ actually executed. On Unix, the *args* name
8308
+ becomes the display name for the executable in utilities such as
8309
+ :program:`ps`. If ``shell=True``, on Unix the *executable* argument
8310
+ specifies a replacement shell for the default :file:`/bin/sh`.
8312
*stdin*, *stdout* and *stderr* specify the executed program's standard input,
8313
standard output and standard error file handles, respectively. Valid values
8314
@@ -377,10 +428,10 @@
8315
.. versionadded:: 3.2
8316
The *pass_fds* parameter was added.
8318
- If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
8319
- before it is executed. Note that this directory is not considered when
8320
- searching the executable, so you can't specify the program's path relative to
8322
+ If *cwd* is not ``None``, the function changes the working directory to
8323
+ *cwd* before executing the child. In particular, the function looks for
8324
+ *executable* (or for the first item in *args*) relative to *cwd* if the
8325
+ executable path is a relative path.
8327
If *restore_signals* is True (the default) all signals that Python has set to
8328
SIG_IGN are restored to SIG_DFL in the child process before the exec.
8329
@@ -408,18 +459,9 @@
6331
8331
.. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
7039
9052
diff -r 3d0686d90f55 Doc/library/timeit.rst
7040
9053
--- a/Doc/library/timeit.rst
7041
9054
+++ b/Doc/library/timeit.rst
7043
may also contain multiple statements separated by ``;`` or newlines, as long as
7044
they don't contain multi-line string literals.
9055
@@ -14,107 +14,157 @@
9058
This module provides a simple way to time small bits of Python code. It has both
9059
-command line as well as callable interfaces. It avoids a number of common traps
9060
-for measuring execution times. See also Tim Peters' introduction to the
9061
-"Algorithms" chapter in the Python Cookbook, published by O'Reilly.
9062
+a :ref:`command-line-interface` as well as a :ref:`callable <python-interface>`
9063
+one. It avoids a number of common traps for measuring execution times.
9064
+See also Tim Peters' introduction to the "Algorithms" chapter in the *Python
9065
+Cookbook*, published by O'Reilly.
9067
-The module defines the following public class:
9072
+The following example shows how the :ref:`command-line-interface`
9073
+can be used to compare three different expressions:
9077
+ $ python -m timeit '"-".join(str(n) for n in range(100))'
9078
+ 10000 loops, best of 3: 40.3 usec per loop
9079
+ $ python -m timeit '"-".join([str(n) for n in range(100)])'
9080
+ 10000 loops, best of 3: 33.4 usec per loop
9081
+ $ python -m timeit '"-".join(map(str, range(100)))'
9082
+ 10000 loops, best of 3: 25.2 usec per loop
9084
+This can be achieved from the :ref:`python-interface` with::
9087
+ >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
9088
+ 0.8187260627746582
9089
+ >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
9090
+ 0.7288308143615723
9091
+ >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
9092
+ 0.5858950614929199
9094
+Note however that :mod:`timeit` will automatically determine the number of
9095
+repetitions only when the command-line interface is used. In the
9096
+:ref:`timeit-examples` section you can find more advanced examples.
9099
+.. _python-interface:
9104
+The module defines three convenience functions and a public class:
9107
+.. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
9109
+ Create a :class:`Timer` instance with the given statement, *setup* code and
9110
+ *timer* function and run its :meth:`.timeit` method with *number* executions.
9113
+.. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)
9115
+ Create a :class:`Timer` instance with the given statement, *setup* code and
9116
+ *timer* function and run its :meth:`.repeat` method with the given *repeat*
9117
+ count and *number* executions.
9120
+.. function:: default_timer()
9122
+ Define a default timer, in a platform-specific manner. On Windows,
9123
+ :func:`time.clock` has microsecond granularity, but :func:`time.time`'s
9124
+ granularity is 1/60th of a second. On Unix, :func:`time.clock` has 1/100th of
9125
+ a second granularity, and :func:`time.time` is much more precise. On either
9126
+ platform, :func:`default_timer` measures wall clock time, not the CPU
9127
+ time. This means that other processes running on the same computer may
9128
+ interfere with the timing.
9131
.. class:: Timer(stmt='pass', setup='pass', timer=<timer function>)
9133
Class for timing execution speed of small code snippets.
9135
- The constructor takes a statement to be timed, an additional statement used for
9136
- setup, and a timer function. Both statements default to ``'pass'``; the timer
9137
- function is platform-dependent (see the module doc string). *stmt* and *setup*
9138
- may also contain multiple statements separated by ``;`` or newlines, as long as
9139
- they don't contain multi-line string literals.
9140
+ The constructor takes a statement to be timed, an additional statement used
9141
+ for setup, and a timer function. Both statements default to ``'pass'``;
9142
+ the timer function is platform-dependent (see the module doc string).
9143
+ *stmt* and *setup* may also contain multiple statements separated by ``;``
9144
+ or newlines, as long as they don't contain multi-line string literals.
7046
9146
- To measure the execution time of the first statement, use the :meth:`timeit`
7047
9147
- method. The :meth:`repeat` method is a convenience to call :meth:`timeit`
7048
+ To measure the execution time of the first statement, use the :meth:`Timer.timeit`
7049
+ method. The :meth:`repeat` method is a convenience to call :meth:`.timeit`
9148
+ To measure the execution time of the first statement, use the :meth:`.timeit`
9149
+ method. The :meth:`.repeat` method is a convenience to call :meth:`.timeit`
7050
9150
multiple times and return a list of results.
7052
9152
The *stmt* and *setup* parameters can also take objects that are callable
7053
without arguments. This will embed calls to them in a timer function that
9153
- without arguments. This will embed calls to them in a timer function that
7054
9154
- will then be executed by :meth:`timeit`. Note that the timing overhead is a
9155
+ without arguments. This will embed calls to them in a timer function that
7055
9156
+ will then be executed by :meth:`.timeit`. Note that the timing overhead is a
7056
9157
little larger in this case because of the extra function calls.
7061
.. method:: Timer.repeat(repeat=3, number=1000000)
9160
-.. method:: Timer.print_exc(file=None)
9161
+ .. method:: Timer.timeit(number=1000000)
9163
- Helper to print a traceback from the timed code.
9164
+ Time *number* executions of the main statement. This executes the setup
9165
+ statement once, and then returns the time it takes to execute the main
9166
+ statement a number of times, measured in seconds as a float.
9167
+ The argument is the number of times through the loop, defaulting to one
9168
+ million. The main statement, the setup statement and the timer function
9169
+ to be used are passed to the constructor.
9174
- t = Timer(...) # outside the try/except
9176
- t.timeit(...) # or t.repeat(...)
9179
+ By default, :meth:`.timeit` temporarily turns off :term:`garbage
9180
+ collection` during the timing. The advantage of this approach is that
9181
+ it makes independent timings more comparable. This disadvantage is
9182
+ that GC may be an important component of the performance of the
9183
+ function being measured. If so, GC can be re-enabled as the first
9184
+ statement in the *setup* string. For example::
9186
- The advantage over the standard traceback is that source lines in the compiled
9187
- template will be displayed. The optional *file* argument directs where the
9188
- traceback is sent; it defaults to ``sys.stderr``.
9189
+ timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
9192
-.. method:: Timer.repeat(repeat=3, number=1000000)
9193
+ .. method:: Timer.repeat(repeat=3, number=1000000)
7063
9195
- Call :meth:`timeit` a few times.
7064
+ Call :meth:`.timeit` a few times.
9196
+ Call :meth:`.timeit` a few times.
7066
9198
- This is a convenience function that calls the :meth:`timeit` repeatedly,
7067
+ This is a convenience function that calls the :meth:`.timeit` repeatedly,
7068
returning a list of results. The first argument specifies how many times to
9199
- returning a list of results. The first argument specifies how many times to
7069
9200
- call :meth:`timeit`. The second argument specifies the *number* argument for
7070
9201
- :func:`timeit`.
7071
+ call :meth:`.timeit`. The second argument specifies the *number* argument for
9202
+ This is a convenience function that calls the :meth:`.timeit` repeatedly,
9203
+ returning a list of results. The first argument specifies how many times
9204
+ to call :meth:`.timeit`. The second argument specifies the *number*
9205
+ argument for :meth:`.timeit`.
9210
- It's tempting to calculate mean and standard deviation from the result vector
9211
- and report these. However, this is not very useful. In a typical case, the
9212
- lowest value gives a lower bound for how fast your machine can run the given
9213
- code snippet; higher values in the result vector are typically not caused by
9214
- variability in Python's speed, but by other processes interfering with your
9215
- timing accuracy. So the :func:`min` of the result is probably the only number
9216
- you should be interested in. After that, you should look at the entire vector
9217
- and apply common sense rather than statistics.
9218
+ It's tempting to calculate mean and standard deviation from the result
9219
+ vector and report these. However, this is not very useful.
9220
+ In a typical case, the lowest value gives a lower bound for how fast
9221
+ your machine can run the given code snippet; higher values in the
9222
+ result vector are typically not caused by variability in Python's
9223
+ speed, but by other processes interfering with your timing accuracy.
9224
+ So the :func:`min` of the result is probably the only number you
9225
+ should be interested in. After that, you should look at the entire
9226
+ vector and apply common sense rather than statistics.
9229
-.. method:: Timer.timeit(number=1000000)
9230
+ .. method:: Timer.print_exc(file=None)
9232
- Time *number* executions of the main statement. This executes the setup
9233
- statement once, and then returns the time it takes to execute the main statement
9234
- a number of times, measured in seconds as a float. The argument is the number
9235
- of times through the loop, defaulting to one million. The main statement, the
9236
- setup statement and the timer function to be used are passed to the constructor.
9237
+ Helper to print a traceback from the timed code.
7080
9242
- By default, :meth:`timeit` temporarily turns off :term:`garbage collection`
7081
+ By default, :meth:`.timeit` temporarily turns off :term:`garbage collection`
7082
during the timing. The advantage of this approach is that it makes
7083
independent timings more comparable. This disadvantage is that GC may be
7084
an important component of the performance of the function being measured.
7086
timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
9243
- during the timing. The advantage of this approach is that it makes
9244
- independent timings more comparable. This disadvantage is that GC may be
9245
- an important component of the performance of the function being measured.
9246
- If so, GC can be re-enabled as the first statement in the *setup* string.
9248
+ t = Timer(...) # outside the try/except
9250
+ t.timeit(...) # or t.repeat(...)
9254
- timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
9255
+ The advantage over the standard traceback is that source lines in the
9256
+ compiled template will be displayed. The optional *file* argument directs
9257
+ where the traceback is sent; it defaults to :data:`sys.stderr`.
7089
9260
-The module also defines two convenience functions:
7090
+The module also defines three convenience functions:
7093
+.. function:: default_timer()
7095
+ Define a default timer, in a platform specific manner. On Windows,
7096
+ :func:`time.clock` has microsecond granularity but :func:`time.time`'s
7097
+ granularity is 1/60th of a second; on Unix, :func:`time.clock` has 1/100th of
7098
+ a second granularity and :func:`time.time` is much more precise. On either
7099
+ platform, :func:`default_timer` measures wall clock time, not the CPU
7100
+ time. This means that other processes running on the same computer may
7101
+ interfere with the timing.
7104
.. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)
7107
.. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
7109
Create a :class:`Timer` instance with the given statement, setup code and timer
9261
+.. _command-line-interface:
9263
-.. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)
9265
- Create a :class:`Timer` instance with the given statement, setup code and timer
9266
- function and run its :meth:`repeat` method with the given repeat count and
9267
- *number* executions.
9270
-.. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
9272
- Create a :class:`Timer` instance with the given statement, setup code and timer
7110
9273
- function and run its :meth:`timeit` method with *number* executions.
7111
+ function and run its :meth:`.timeit` method with *number* executions.
7114
Command Line Interface
7115
@@ -161,13 +173,9 @@
9276
-Command Line Interface
9277
+Command-Line Interface
9278
----------------------
9280
When called as a program from the command line, the following form is used::
9281
@@ -161,13 +211,9 @@
7116
9282
If :option:`-n` is not given, a suitable number of loops is calculated by trying
7117
9283
successive powers of 10 until the total time is at least 0.2 seconds.
17680
21425
import tempfile
17681
@@ -476,21 +477,22 @@
21426
@@ -163,24 +165,108 @@
21428
self.assertEqual(p.stderr, None)
21430
+ # For use in the test_cwd* tests below.
21431
+ def _normalize_cwd(self, cwd):
21432
+ # Normalize an expected cwd (for Tru64 support).
21433
+ # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
21434
+ # strings. See bug #1063571.
21435
+ original_cwd = os.getcwd()
21437
+ cwd = os.getcwd()
21438
+ os.chdir(original_cwd)
21441
+ # For use in the test_cwd* tests below.
21442
+ def _split_python_path(self):
21443
+ # Return normalized (python_dir, python_base).
21444
+ python_path = os.path.realpath(sys.executable)
21445
+ return os.path.split(python_path)
21447
+ # For use in the test_cwd* tests below.
21448
+ def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
21449
+ # Invoke Python via Popen, and assert that (1) the call succeeds,
21450
+ # and that (2) the current working directory of the child process
21451
+ # matches *expected_cwd*.
21452
+ p = subprocess.Popen([python_arg, "-c",
21453
+ "import os, sys; "
21454
+ "sys.stdout.write(os.getcwd()); "
21456
+ stdout=subprocess.PIPE,
21458
+ self.addCleanup(p.stdout.close)
21460
+ self.assertEqual(47, p.returncode)
21461
+ normcase = os.path.normcase
21462
+ self.assertEqual(normcase(expected_cwd),
21463
+ normcase(p.stdout.read().decode("utf-8")))
21465
+ def test_cwd(self):
21466
+ # Check that cwd changes the cwd for the child process.
21467
+ temp_dir = tempfile.gettempdir()
21468
+ temp_dir = self._normalize_cwd(temp_dir)
21469
+ self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
21471
+ @unittest.skipIf(mswindows, "pending resolution of issue #15533")
21472
+ def test_cwd_with_relative_arg(self):
21473
+ # Check that Popen looks for args[0] relative to cwd if args[0]
21475
+ python_dir, python_base = self._split_python_path()
21476
+ rel_python = os.path.join(os.curdir, python_base)
21477
+ with support.temp_cwd() as wrong_dir:
21478
+ # Before calling with the correct cwd, confirm that the call fails
21479
+ # without cwd and with the wrong cwd.
21480
+ self.assertRaises(OSError, subprocess.Popen,
21482
+ self.assertRaises(OSError, subprocess.Popen,
21483
+ [rel_python], cwd=wrong_dir)
21484
+ python_dir = self._normalize_cwd(python_dir)
21485
+ self._assert_cwd(python_dir, rel_python, cwd=python_dir)
21487
+ @unittest.skipIf(mswindows, "pending resolution of issue #15533")
21488
+ def test_cwd_with_relative_executable(self):
21489
+ # Check that Popen looks for executable relative to cwd if executable
21490
+ # is relative (and that executable takes precedence over args[0]).
21491
+ python_dir, python_base = self._split_python_path()
21492
+ rel_python = os.path.join(os.curdir, python_base)
21493
+ doesntexist = "somethingyoudonthave"
21494
+ with support.temp_cwd() as wrong_dir:
21495
+ # Before calling with the correct cwd, confirm that the call fails
21496
+ # without cwd and with the wrong cwd.
21497
+ self.assertRaises(OSError, subprocess.Popen,
21498
+ [doesntexist], executable=rel_python)
21499
+ self.assertRaises(OSError, subprocess.Popen,
21500
+ [doesntexist], executable=rel_python,
21502
+ python_dir = self._normalize_cwd(python_dir)
21503
+ self._assert_cwd(python_dir, doesntexist, executable=rel_python,
21506
+ def test_cwd_with_absolute_arg(self):
21507
+ # Check that Popen can find the executable when the cwd is wrong
21508
+ # if args[0] is an absolute path.
21509
+ python_dir, python_base = self._split_python_path()
21510
+ abs_python = os.path.join(python_dir, python_base)
21511
+ rel_python = os.path.join(os.curdir, python_base)
21512
+ with script_helper.temp_dir() as wrong_dir:
21513
+ # Before calling with an absolute path, confirm that using a
21514
+ # relative path fails.
21515
+ self.assertRaises(OSError, subprocess.Popen,
21516
+ [rel_python], cwd=wrong_dir)
21517
+ wrong_dir = self._normalize_cwd(wrong_dir)
21518
+ self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
21520
def test_executable_with_cwd(self):
21521
- python_dir = os.path.dirname(os.path.realpath(sys.executable))
21522
- p = subprocess.Popen(["somethingyoudonthave", "-c",
21523
- "import sys; sys.exit(47)"],
21524
- executable=sys.executable, cwd=python_dir)
21526
- self.assertEqual(p.returncode, 47)
21527
+ python_dir, python_base = self._split_python_path()
21528
+ python_dir = self._normalize_cwd(python_dir)
21529
+ self._assert_cwd(python_dir, "somethingyoudonthave",
21530
+ executable=sys.executable, cwd=python_dir)
21532
@unittest.skipIf(sysconfig.is_python_build(),
21533
"need an installed Python. See #7774")
21534
def test_executable_without_cwd(self):
21535
# For a normal installation, it should work without 'cwd'
21536
# argument. For test runs in the build directory, see #7774.
21537
- p = subprocess.Popen(["somethingyoudonthave", "-c",
21538
- "import sys; sys.exit(47)"],
21539
- executable=sys.executable)
21541
- self.assertEqual(p.returncode, 47)
21542
+ self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
21544
def test_stdin_pipe(self):
21545
# stdin redirection
21546
@@ -312,24 +398,6 @@
21547
rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
21548
self.assertEqual(rc, 2)
21550
- def test_cwd(self):
21551
- tmpdir = tempfile.gettempdir()
21552
- # We cannot use os.path.realpath to canonicalize the path,
21553
- # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
21554
- cwd = os.getcwd()
21556
- tmpdir = os.getcwd()
21558
- p = subprocess.Popen([sys.executable, "-c",
21560
- 'sys.stdout.write(os.getcwd())'],
21561
- stdout=subprocess.PIPE,
21563
- self.addCleanup(p.stdout.close)
21564
- normcase = os.path.normcase
21565
- self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
21566
- normcase(tmpdir))
21568
def test_env(self):
21569
newenv = os.environ.copy()
21570
newenv["FRUIT"] = "orange"
21571
@@ -476,21 +544,22 @@
17682
21572
def test_universal_newlines(self):
17683
21573
p = subprocess.Popen([sys.executable, "-c",
17684
21574
'import sys,os;' + SETBINARY +