Skip to content
This repository was archived by the owner on Feb 13, 2025. It is now read-only.

Commit b5aa291

Browse files
author
Anselm Kruis
committed
merge branch 3.5
2 parents bd0ab1a + 9c8213f commit b5aa291

File tree

144 files changed

+2782
-1075
lines changed

Some content is hidden

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

144 files changed

+2782
-1075
lines changed

Doc/c-api/code.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ bound into a function.
2929

3030
.. c:function:: int PyCode_Check(PyObject *co)
3131
32-
Return true if *co* is a :class:`code` object
32+
Return true if *co* is a :class:`code` object.
3333
3434
.. c:function:: int PyCode_GetNumFree(PyCodeObject *co)
3535

Doc/c-api/gen.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ than explicitly calling :c:func:`PyGen_New` or :c:func:`PyGen_NewWithQualName`.
1717

1818
.. c:var:: PyTypeObject PyGen_Type
1919
20-
The type object corresponding to generator objects
20+
The type object corresponding to generator objects.
2121

2222

2323
.. c:function:: int PyGen_Check(PyObject *ob)

Doc/c-api/veryhigh.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ the same library that the Python runtime is using.
201201
.. c:function:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
202202
203203
This is a simplified interface to :c:func:`PyParser_SimpleParseFileFlags` below,
204-
leaving *flags* set to ``0``
204+
leaving *flags* set to ``0``.
205205
206206
207207
.. c:function:: struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)

Doc/distutils/apiref.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -928,7 +928,7 @@ timestamp dependency analysis.
928928

929929
Walk two filename lists in parallel, testing if each source is newer than its
930930
corresponding target. Return a pair of lists (*sources*, *targets*) where
931-
source is newer than target, according to the semantics of :func:`newer`
931+
source is newer than target, according to the semantics of :func:`newer`.
932932

933933
.. % % equivalent to a listcomp...
934934

Doc/faq/extending.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -443,8 +443,8 @@ extension module using g++ (e.g., ``g++ -shared -o mymodule.so mymodule.o``).
443443
Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?
444444
----------------------------------------------------------------------------------------------------------------
445445

446-
In Python 2.2, you can inherit from built-in classes such as :class:`int`,
447-
:class:`list`, :class:`dict`, etc.
446+
Yes, you can inherit from built-in classes such as :class:`int`, :class:`list`,
447+
:class:`dict`, etc.
448448

449449
The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html)
450450
provides a way of doing this from C++ (i.e. you can inherit from an extension

Doc/glossary.rst

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,14 @@ Glossary
241241
keys can be any object with :meth:`__hash__` and :meth:`__eq__` methods.
242242
Called a hash in Perl.
243243

244+
dictionary view
245+
The objects returned from :meth:`dict.keys`, :meth:`dict.values`, and
246+
:meth:`dict.items` are called dictionary views. They provide a dynamic
247+
view on the dictionary’s entries, which means that when the dictionary
248+
changes, the view reflects these changes. To force the
249+
dictionary view to become a full list use ``list(dictview)``. See
250+
:ref:`dict-views`.
251+
244252
docstring
245253
A string literal which appears as the first expression in a class,
246254
function or module. While ignored when the suite is executed, it is
@@ -934,20 +942,13 @@ Glossary
934942
``'\r'``. See :pep:`278` and :pep:`3116`, as well as
935943
:func:`bytes.splitlines` for an additional use.
936944

937-
view
938-
The objects returned from :meth:`dict.keys`, :meth:`dict.values`, and
939-
:meth:`dict.items` are called dictionary views. They are lazy sequences
940-
that will see changes in the underlying dictionary. To force the
941-
dictionary view to become a full list use ``list(dictview)``. See
942-
:ref:`dict-views`.
943-
944945
virtual environment
945946
A cooperatively isolated runtime environment that allows Python users
946947
and applications to install and upgrade Python distribution packages
947948
without interfering with the behaviour of other Python applications
948949
running on the same system.
949950

950-
See also :ref:`scripts-pyvenv`
951+
See also :ref:`scripts-pyvenv`.
951952

952953
virtual machine
953954
A computer defined entirely in software. Python's virtual machine

Doc/howto/logging-cookbook.rst

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2151,3 +2151,140 @@ The above approach can, of course, be adapted to other TTS systems and even
21512151
other systems altogether which can process messages via external programs run
21522152
from a command line.
21532153

2154+
2155+
.. _buffered-logging:
2156+
2157+
Buffering logging messages and outputting them conditionally
2158+
------------------------------------------------------------
2159+
2160+
There might be situations where you want to log messages in a temporary area
2161+
and only output them if a certain condition occurs. For example, you may want to
2162+
start logging debug events in a function, and if the function completes without
2163+
errors, you don't want to clutter the log with the collected debug information,
2164+
but if there is an error, you want all the debug information to be output as well
2165+
as the error.
2166+
2167+
Here is an example which shows how you could do this using a decorator for your
2168+
functions where you want logging to behave this way. It makes use of the
2169+
:class:`logging.handlers.MemoryHandler`, which allows buffering of logged events
2170+
until some condition occurs, at which point the buffered events are ``flushed``
2171+
- passed to another handler (the ``target`` handler) for processing. By default,
2172+
the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose
2173+
level is greater than or equal to a specified threshold is seen. You can use this
2174+
recipe with a more specialised subclass of ``MemoryHandler`` if you want custom
2175+
flushing behavior.
2176+
2177+
The example script has a simple function, ``foo``, which just cycles through
2178+
all the logging levels, writing to ``sys.stderr`` to say what level it's about
2179+
to log at, and then actually logging a message that that level. You can pass a
2180+
parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels -
2181+
otherwise, it only logs at DEBUG, INFO and WARNING levels.
2182+
2183+
The script just arranges to decorate ``foo`` with a decorator which will do the
2184+
conditional logging that's required. The decorator takes a logger as a parameter
2185+
and attaches a memory handler for the duration of the call to the decorated
2186+
function. The decorator can be additionally parameterised using a target handler,
2187+
a level at which flushing should occur, and a capacity for the buffer. These
2188+
default to a :class:`~logging.StreamHandler` which writes to ``sys.stderr``,
2189+
``logging.ERROR`` and ``100`` respectively.
2190+
2191+
Here's the script::
2192+
2193+
import logging
2194+
from logging.handlers import MemoryHandler
2195+
import sys
2196+
2197+
logger = logging.getLogger(__name__)
2198+
logger.addHandler(logging.NullHandler())
2199+
2200+
def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
2201+
if target_handler is None:
2202+
target_handler = logging.StreamHandler()
2203+
if flush_level is None:
2204+
flush_level = logging.ERROR
2205+
if capacity is None:
2206+
capacity = 100
2207+
handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)
2208+
2209+
def decorator(fn):
2210+
def wrapper(*args, **kwargs):
2211+
logger.addHandler(handler)
2212+
try:
2213+
return fn(*args, **kwargs)
2214+
except Exception:
2215+
logger.exception('call failed')
2216+
raise
2217+
finally:
2218+
super(MemoryHandler, handler).flush()
2219+
logger.removeHandler(handler)
2220+
return wrapper
2221+
2222+
return decorator
2223+
2224+
def write_line(s):
2225+
sys.stderr.write('%s\n' % s)
2226+
2227+
def foo(fail=False):
2228+
write_line('about to log at DEBUG ...')
2229+
logger.debug('Actually logged at DEBUG')
2230+
write_line('about to log at INFO ...')
2231+
logger.info('Actually logged at INFO')
2232+
write_line('about to log at WARNING ...')
2233+
logger.warning('Actually logged at WARNING')
2234+
if fail:
2235+
write_line('about to log at ERROR ...')
2236+
logger.error('Actually logged at ERROR')
2237+
write_line('about to log at CRITICAL ...')
2238+
logger.critical('Actually logged at CRITICAL')
2239+
return fail
2240+
2241+
decorated_foo = log_if_errors(logger)(foo)
2242+
2243+
if __name__ == '__main__':
2244+
logger.setLevel(logging.DEBUG)
2245+
write_line('Calling undecorated foo with False')
2246+
assert not foo(False)
2247+
write_line('Calling undecorated foo with True')
2248+
assert foo(True)
2249+
write_line('Calling decorated foo with False')
2250+
assert not decorated_foo(False)
2251+
write_line('Calling decorated foo with True')
2252+
assert decorated_foo(True)
2253+
2254+
When this script is run, the following output should be observed::
2255+
2256+
Calling undecorated foo with False
2257+
about to log at DEBUG ...
2258+
about to log at INFO ...
2259+
about to log at WARNING ...
2260+
Calling undecorated foo with True
2261+
about to log at DEBUG ...
2262+
about to log at INFO ...
2263+
about to log at WARNING ...
2264+
about to log at ERROR ...
2265+
about to log at CRITICAL ...
2266+
Calling decorated foo with False
2267+
about to log at DEBUG ...
2268+
about to log at INFO ...
2269+
about to log at WARNING ...
2270+
Calling decorated foo with True
2271+
about to log at DEBUG ...
2272+
about to log at INFO ...
2273+
about to log at WARNING ...
2274+
about to log at ERROR ...
2275+
Actually logged at DEBUG
2276+
Actually logged at INFO
2277+
Actually logged at WARNING
2278+
Actually logged at ERROR
2279+
about to log at CRITICAL ...
2280+
Actually logged at CRITICAL
2281+
2282+
As you can see, actual logging output only occurs when an event is logged whose
2283+
severity is ERROR or greater, but in that case, any previous events at lower
2284+
severities are also logged.
2285+
2286+
You can of course use the conventional means of decoration::
2287+
2288+
@log_if_errors(logger)
2289+
def foo(fail=False):
2290+
...

Doc/library/2to3.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ and off individually. They are described here in more detail.
271271
272272
.. 2to3fixer:: input
273273
274-
Converts ``input(prompt)`` to ``eval(input(prompt))``
274+
Converts ``input(prompt)`` to ``eval(input(prompt))``.
275275
276276
.. 2to3fixer:: intern
277277

Doc/library/argparse.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2011,4 +2011,4 @@ A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
20112011
``%(default)s`` and ``%(prog)s``.
20122012

20132013
* Replace the OptionParser constructor ``version`` argument with a call to
2014-
``parser.add_argument('--version', action='version', version='<the version>')``
2014+
``parser.add_argument('--version', action='version', version='<the version>')``.

Doc/library/asyncio-dev.rst

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,10 +96,9 @@ the same thread. But when the task uses ``yield from``, the task is suspended
9696
and the event loop executes the next task.
9797

9898
To schedule a callback from a different thread, the
99-
:meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example to
100-
schedule a coroutine from a different thread::
99+
:meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example::
101100

102-
loop.call_soon_threadsafe(asyncio.ensure_future, coro_func())
101+
loop.call_soon_threadsafe(callback, *args)
103102

104103
Most asyncio objects are not thread safe. You should only worry if you access
105104
objects outside the event loop. For example, to cancel a future, don't call
@@ -110,6 +109,13 @@ directly its :meth:`Future.cancel` method, but::
110109
To handle signals and to execute subprocesses, the event loop must be run in
111110
the main thread.
112111

112+
To schedule a coroutine object from a different thread, the
113+
:func:`run_coroutine_threadsafe` function should be used. It returns a
114+
:class:`concurrent.futures.Future` to access the result::
115+
116+
future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
117+
result = future.result(timeout) # Wait for the result with a timeout
118+
113119
The :meth:`BaseEventLoop.run_in_executor` method can be used with a thread pool
114120
executor to execute a callback in different thread to not block the thread of
115121
the event loop.

Doc/library/asyncio-eventloop.rst

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -285,17 +285,50 @@ Creating connections
285285
(:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
286286

287287

288-
.. coroutinemethod:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
288+
.. coroutinemethod:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)
289289

290290
Create datagram connection: socket family :py:data:`~socket.AF_INET` or
291291
:py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
292-
socket type :py:data:`~socket.SOCK_DGRAM`.
292+
socket type :py:data:`~socket.SOCK_DGRAM`. *protocol_factory* must be a
293+
callable returning a :ref:`protocol <asyncio-protocol>` instance.
293294

294295
This method is a :ref:`coroutine <coroutine>` which will try to
295296
establish the connection in the background. When successful, the
296297
coroutine returns a ``(transport, protocol)`` pair.
297298

298-
See the :meth:`BaseEventLoop.create_connection` method for parameters.
299+
Options changing how the connection is created:
300+
301+
* *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
302+
to bind the socket to locally. The *local_host* and *local_port*
303+
are looked up using :meth:`getaddrinfo`.
304+
305+
* *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
306+
to connect the socket to a remote address. The *remote_host* and
307+
*remote_port* are looked up using :meth:`getaddrinfo`.
308+
309+
* *family*, *proto*, *flags* are the optional address family, protocol
310+
and flags to be passed through to :meth:`getaddrinfo` for *host*
311+
resolution. If given, these should all be integers from the
312+
corresponding :mod:`socket` module constants.
313+
314+
* *reuse_address* tells the kernel to reuse a local socket in
315+
TIME_WAIT state, without waiting for its natural timeout to
316+
expire. If not specified will automatically be set to True on
317+
UNIX.
318+
319+
* *reuse_port* tells the kernel to allow this endpoint to be bound to the
320+
same port as other existing endpoints are bound to, so long as they all
321+
set this flag when being created. This option is not supported on Windows
322+
and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
323+
defined then this capability is unsupported.
324+
325+
* *allow_broadcast* tells the kernel to allow this endpoint to send
326+
messages to the broadcast address.
327+
328+
* *sock* can optionally be specified in order to use a preexisting,
329+
already connected, :class:`socket.socket` object to be used by the
330+
transport. If specified, *local_addr* and *remote_addr* should be omitted
331+
(must be :const:`None`).
299332

300333
On Windows with :class:`ProactorEventLoop`, this method is not supported.
301334

@@ -322,7 +355,7 @@ Creating connections
322355
Creating listening connections
323356
------------------------------
324357

325-
.. coroutinemethod:: BaseEventLoop.create_server(protocol_factory, host=None, port=None, \*, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None)
358+
.. coroutinemethod:: BaseEventLoop.create_server(protocol_factory, host=None, port=None, \*, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None)
326359

327360
Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
328361
*host* and *port*.
@@ -361,6 +394,11 @@ Creating listening connections
361394
expire. If not specified will automatically be set to True on
362395
UNIX.
363396

397+
* *reuse_port* tells the kernel to allow this endpoint to be bound to the
398+
same port as other existing endpoints are bound to, so long as they all
399+
set this flag when being created. This option is not supported on
400+
Windows.
401+
364402
This method is a :ref:`coroutine <coroutine>`.
365403

366404
.. versionchanged:: 3.5
@@ -586,14 +624,14 @@ Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
586624
pool of processes). By default, an event loop uses a thread pool executor
587625
(:class:`~concurrent.futures.ThreadPoolExecutor`).
588626

589-
.. coroutinemethod:: BaseEventLoop.run_in_executor(executor, callback, \*args)
627+
.. coroutinemethod:: BaseEventLoop.run_in_executor(executor, func, \*args)
590628

591-
Arrange for a callback to be called in the specified executor.
629+
Arrange for a *func* to be called in the specified executor.
592630

593631
The *executor* argument should be an :class:`~concurrent.futures.Executor`
594632
instance. The default executor is used if *executor* is ``None``.
595633

596-
:ref:`Use functools.partial to pass keywords to the callback
634+
:ref:`Use functools.partial to pass keywords to the *func*
597635
<asyncio-pass-keywords>`.
598636

599637
This method is a :ref:`coroutine <coroutine>`.

Doc/library/asyncio-protocol.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ BaseSubprocessTransport
232232

233233
.. method:: kill(self)
234234

235-
Kill the subprocess, as in :meth:`subprocess.Popen.kill`
235+
Kill the subprocess, as in :meth:`subprocess.Popen.kill`.
236236

237237
On POSIX systems, the function sends SIGKILL to the subprocess.
238238
On Windows, this method is an alias for :meth:`terminate`.

0 commit comments

Comments
 (0)