From d2d58ca5f97fd12cc4feb945a36fb66cd1268d1f Mon Sep 17 00:00:00 2001 From: Colin Marquardt Date: Sun, 11 May 2025 18:08:51 +0200 Subject: [PATCH 1/2] gh-133905: Fix parsing problems in example code --- Doc/faq/programming.rst | 7 ++++--- Doc/howto/ipaddress.rst | 1 + Doc/howto/logging.rst | 2 +- Doc/howto/urllib2.rst | 2 ++ Doc/library/argparse.rst | 2 +- Doc/library/ast.rst | 2 +- Doc/library/asyncio-eventloop.rst | 1 + Doc/library/asyncio-sync.rst | 4 ++++ Doc/library/contextlib.rst | 9 +++++++++ Doc/library/dataclasses.rst | 3 +++ Doc/library/decimal.rst | 4 ++-- Doc/library/dis.rst | 2 +- Doc/library/inspect.rst | 1 + Doc/library/logging.config.rst | 2 +- Doc/library/logging.rst | 1 + Doc/library/multiprocessing.rst | 6 ++++-- Doc/library/sys.rst | 1 + Doc/library/test.rst | 20 +++++++++++++------- Doc/library/threading.rst | 3 +++ Doc/library/tkinter.rst | 1 + Doc/library/urllib.request.rst | 2 +- Doc/library/weakref.rst | 1 + Doc/tutorial/classes.rst | 1 + Doc/tutorial/controlflow.rst | 1 + Doc/whatsnew/2.0.rst | 1 + Doc/whatsnew/2.3.rst | 6 +++--- Doc/whatsnew/3.7.rst | 1 + Doc/whatsnew/3.8.rst | 3 ++- 28 files changed, 66 insertions(+), 24 deletions(-) diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst index 776bab1ed5b779..ff85c737abec8e 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -340,7 +340,7 @@ Why are default values shared between objects? This type of bug commonly bites neophyte programmers. Consider this function:: def foo(mydict={}): # Danger: shared reference to one dict for all calls - ... compute something ... + # ... compute something ... mydict[key] = value return mydict @@ -382,7 +382,7 @@ requested again. This is called "memoizing", and can be implemented like this:: return _cache[(arg1, arg2)] # Calculate the value - result = ... expensive computation ... + result = ... # ... expensive computation ... _cache[(arg1, arg2)] = result # Store result in the cache return result @@ -1555,7 +1555,8 @@ that does something:: ... # code to search a mailbox elif isinstance(obj, Document): ... # code to search a document - elif ... + elif ...: + ... A better approach is to define a ``search()`` method on all the classes and just call it:: diff --git a/Doc/howto/ipaddress.rst b/Doc/howto/ipaddress.rst index e852db98156fac..5651f980f8b97c 100644 --- a/Doc/howto/ipaddress.rst +++ b/Doc/howto/ipaddress.rst @@ -255,6 +255,7 @@ membership test syntax like this:: if address in network: # do something + ... Containment testing is done efficiently based on the network prefix:: diff --git a/Doc/howto/logging.rst b/Doc/howto/logging.rst index 2982cf88bf97b4..947f0059a0919e 100644 --- a/Doc/howto/logging.rst +++ b/Doc/howto/logging.rst @@ -190,7 +190,7 @@ following example:: numeric_level = getattr(logging, loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % loglevel) - logging.basicConfig(level=numeric_level, ...) + logging.basicConfig(..., level=numeric_level) The call to :func:`basicConfig` should come *before* any calls to a logger's methods such as :meth:`~Logger.debug`, :meth:`~Logger.info`, etc. Otherwise, diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst index 33a2a7ea89ea07..9346b5d2333d4b 100644 --- a/Doc/howto/urllib2.rst +++ b/Doc/howto/urllib2.rst @@ -360,6 +360,7 @@ Number 1 print('Reason: ', e.reason) else: # everything is fine + ... .. note:: @@ -386,6 +387,7 @@ Number 2 print('Error code: ', e.code) else: # everything is fine + ... info and geturl diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index 8d0116d8c060b8..8a409d8a077cfb 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -698,7 +698,7 @@ upper-cased name. For example:: >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('--foo-bar') - >>> parser.parse_args(['--foo-bar', 'FOO-BAR'] + >>> parser.parse_args(['--foo-bar', 'FOO-BAR']) Namespace(foo_bar='FOO-BAR') >>> parser.print_help() usage: [-h] [--foo-bar FOO-BAR] diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst index fd901e232855b5..d5a6444f7495cd 100644 --- a/Doc/library/ast.rst +++ b/Doc/library/ast.rst @@ -9,7 +9,7 @@ .. testsetup:: - import ast + import ast **Source code:** :source:`Lib/ast.py` diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst index 15ef33e195904d..15a040442caf23 100644 --- a/Doc/library/asyncio-eventloop.rst +++ b/Doc/library/asyncio-eventloop.rst @@ -1656,6 +1656,7 @@ Do not instantiate the :class:`Server` class directly. async with srv: # some code + ... # At this point, srv is closed and no longer accepts new connections. diff --git a/Doc/library/asyncio-sync.rst b/Doc/library/asyncio-sync.rst index 77c2e97da11990..c0e1c807b69725 100644 --- a/Doc/library/asyncio-sync.rst +++ b/Doc/library/asyncio-sync.rst @@ -52,6 +52,7 @@ Lock # ... later async with lock: # access shared state + ... which is equivalent to:: @@ -61,6 +62,7 @@ Lock await lock.acquire() try: # access shared state + ... finally: lock.release() @@ -300,6 +302,7 @@ Semaphore # ... later async with sem: # work with shared resource + ... which is equivalent to:: @@ -309,6 +312,7 @@ Semaphore await sem.acquire() try: # work with shared resource + ... finally: sem.release() diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst index e8f264f949807d..9f2c083b947400 100644 --- a/Doc/library/contextlib.rst +++ b/Doc/library/contextlib.rst @@ -69,6 +69,7 @@ Functions and classes provided: The function can then be used like this:: >>> with managed_resource(timeout=3600) as resource: + ... ... ... # Resource is released at the end of this block, ... # even if code in the block raises an exception @@ -145,6 +146,7 @@ Functions and classes provided: @timeit() async def main(): # ... async code ... + ... When used as a decorator, a new generator instance is implicitly created on each function call. This allows the otherwise "one-shot" context managers @@ -241,6 +243,7 @@ Functions and classes provided: cm = contextlib.nullcontext() with cm: # Do something + ... An example using *enter_result*:: @@ -254,6 +257,7 @@ Functions and classes provided: with cm as file: # Perform processing on the file + ... It can also be used as a stand-in for :ref:`asynchronous context managers `:: @@ -268,6 +272,7 @@ Functions and classes provided: async with cm as session: # Send http requests with session + ... .. versionadded:: 3.7 @@ -438,12 +443,14 @@ Functions and classes provided: def f(): with cm(): # Do stuff + ... ``ContextDecorator`` lets you instead write:: @cm() def f(): # Do stuff + ... It makes it clear that the ``cm`` applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too). @@ -706,9 +713,11 @@ protocol can be separated slightly in order to allow this:: x = stack.enter_context(cm) except Exception: # handle __enter__ exception + ... else: with stack: # Handle normal case + ... Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index e34b2db0210960..28bb81789020be 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -226,6 +226,7 @@ Module contents :meth:`~object.__init__` method, which will be defined as:: def __init__(self, a: int, b: int = 0): + ... :exc:`TypeError` will be raised if a field without a default value follows a field with a default value. This is true whether this @@ -670,6 +671,7 @@ type of :attr:`!x` is :class:`int`, as specified in class :class:`!C`. The generated :meth:`~object.__init__` method for :class:`!C` will look like:: def __init__(self, x: int = 15, y: int = 0, z: int = 10): + ... Re-ordering of keyword-only parameters in :meth:`!__init__` ----------------------------------------------------------- @@ -698,6 +700,7 @@ fields, and :attr:`!Base.x` and :attr:`!D.z` are regular fields:: The generated :meth:`!__init__` method for :class:`!D` will look like:: def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0): + ... Note that the parameters have been re-ordered from how they appear in the list of fields: parameters derived from regular fields are diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst index 9318af60b60f95..9d17784c587328 100644 --- a/Doc/library/decimal.rst +++ b/Doc/library/decimal.rst @@ -1903,7 +1903,7 @@ threads calling :func:`getcontext`. For example:: t1.start() t2.start() t3.start() - . . . + ... .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -2165,7 +2165,7 @@ applied to the *result* of the computation:: Decimal('3.1416') >>> pi - Decimal('0.00005') # Subtract unrounded numbers, then round Decimal('3.1415') - >>> pi + 0 - Decimal('0.00005'). # Intermediate values are rounded + >>> pi + 0 - Decimal('0.00005') # Intermediate values are rounded Decimal('3.1416') Q. Some decimal values always print with exponential notation. Is there a way diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst index d914acbbc67076..51224a5735f21b 100644 --- a/Doc/library/dis.rst +++ b/Doc/library/dis.rst @@ -700,7 +700,7 @@ not have to be) the original ``STACK[-2]``. rhs = STACK.pop() lhs = STACK.pop() - STACK.append(lhs op rhs) + STACK.append(lhs, op, rhs) .. versionadded:: 3.11 .. versionchanged:: 3.14 diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index e8d1176f477866..7d6a5cf952e7a3 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -1405,6 +1405,7 @@ is considered deprecated and may be removed in the future. frame = inspect.currentframe() try: # do something with the frame + ... finally: del frame diff --git a/Doc/library/logging.config.rst b/Doc/library/logging.config.rst index 0e9dc33ae2123a..9315db6d85196c 100644 --- a/Doc/library/logging.config.rst +++ b/Doc/library/logging.config.rst @@ -558,7 +558,7 @@ following configuration:: 'bar' : 'baz', 'spam' : 99.9, 'answer' : 42, - '.' { + '.' : { 'foo': 'bar', 'baz': 'bozz' } diff --git a/Doc/library/logging.rst b/Doc/library/logging.rst index 34bb46f0bb1ecb..b28913ece7f8fc 100644 --- a/Doc/library/logging.rst +++ b/Doc/library/logging.rst @@ -1176,6 +1176,7 @@ functions. class MyLogger(logging.getLoggerClass()): # ... override behaviour here + ... .. function:: getLogRecordFactory() diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index 783cb025826483..557c577d191860 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -2935,7 +2935,8 @@ Explicitly pass resources to child processes from multiprocessing import Process, Lock def f(): - ... do something using "lock" ... + # ... do something using "lock" ... + ... if __name__ == '__main__': lock = Lock() @@ -2947,7 +2948,8 @@ Explicitly pass resources to child processes from multiprocessing import Process, Lock def f(l): - ... do something using "l" ... + # ... do something using "l" ... + ... if __name__ == '__main__': lock = Lock() diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index eaa8aa711db173..f2d68456ca7e4b 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -1462,6 +1462,7 @@ always available. Unless explicitly noted otherwise, all variables are read-only if sys.platform.startswith('sunos'): # SunOS-specific code here... + ... .. versionchanged:: 3.3 On Linux, :data:`sys.platform` doesn't contain the major version anymore. diff --git a/Doc/library/test.rst b/Doc/library/test.rst index def22f8bb8ab2d..2c5dabdcd9fe4e 100644 --- a/Doc/library/test.rst +++ b/Doc/library/test.rst @@ -62,25 +62,30 @@ A basic boilerplate is often used:: # Only use setUp() and tearDown() if necessary def setUp(self): - ... code to execute in preparation for tests ... + # ... code to execute in preparation for tests ... + ... def tearDown(self): - ... code to execute to clean up after tests ... + # ... code to execute to clean up after tests ... + ... def test_feature_one(self): # Test feature one. - ... testing code ... + # ... testing code ... + ... def test_feature_two(self): # Test feature two. - ... testing code ... + # ... testing code ... + ... - ... more test methods ... + # ... more test methods ... class MyTestCase2(unittest.TestCase): - ... same structure as MyTestCase1 ... + # ... same structure as MyTestCase1 ... + ... - ... more test classes ... + # ... more test classes ... if __name__ == '__main__': unittest.main() @@ -1683,6 +1688,7 @@ The :mod:`test.support.warnings_helper` module provides support for warnings tes @warning_helper.ignore_warnings(category=DeprecationWarning) def test_suppress_warning(): # do something + ... .. versionadded:: 3.8 diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst index 00511df32e4388..2352f372a21eba 100644 --- a/Doc/library/threading.rst +++ b/Doc/library/threading.rst @@ -983,6 +983,7 @@ when they need to connect to the server:: conn = connectdb() try: # ... use connection ... + ... finally: conn.close() @@ -1202,12 +1203,14 @@ the following snippet:: with some_lock: # do something... + ... is equivalent to:: some_lock.acquire() try: # do something... + ... finally: some_lock.release() diff --git a/Doc/library/tkinter.rst b/Doc/library/tkinter.rst index f284988daf2d4e..c3edf6123ef3b0 100644 --- a/Doc/library/tkinter.rst +++ b/Doc/library/tkinter.rst @@ -872,6 +872,7 @@ and to have a callback function trigger when that event type occurs. The form of the bind method is:: def bind(self, sequence, func, add=''): + ... where: diff --git a/Doc/library/urllib.request.rst b/Doc/library/urllib.request.rst index b3efde3f189566..06ed756bce28bf 100644 --- a/Doc/library/urllib.request.rst +++ b/Doc/library/urllib.request.rst @@ -1375,7 +1375,7 @@ environment settings:: The following example uses no proxies at all, overriding environment settings:: >>> import urllib.request - >>> opener = urllib.request.build_opener(urllib.request.ProxyHandler({}})) + >>> opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) >>> with opener.open("http://www.python.org/") as f: ... f.read().decode('utf-8') ... diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst index 2a25ed045c68bd..215f38bd4f0344 100644 --- a/Doc/library/weakref.rst +++ b/Doc/library/weakref.rst @@ -588,6 +588,7 @@ third party, such as running code when a module is unloaded:: import weakref, sys def unloading_module(): # implicit reference to the module globals from the function body + ... weakref.finalize(sys.modules[__name__], unloading_module) diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst index 9d0fab8861d2a9..4d4071a95fae82 100644 --- a/Doc/tutorial/classes.rst +++ b/Doc/tutorial/classes.rst @@ -583,6 +583,7 @@ expressions are also allowed. This can be useful, for example, when the base class is defined in another module:: class DerivedClassName(modname.BaseClassName): + ... Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst index 8261bbdbfb7a01..3fcac54866dcf0 100644 --- a/Doc/tutorial/controlflow.rst +++ b/Doc/tutorial/controlflow.rst @@ -896,6 +896,7 @@ Recap The use case will determine which parameters to use in the function definition:: def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): + ... As guidance: diff --git a/Doc/whatsnew/2.0.rst b/Doc/whatsnew/2.0.rst index 1a949ec4035807..e1ed0e5608a2c1 100644 --- a/Doc/whatsnew/2.0.rst +++ b/Doc/whatsnew/2.0.rst @@ -315,6 +315,7 @@ following Python code:: # Append the value of # the expression to the # resulting list. + ... This means that when there are multiple :keyword:`!for`...\ :keyword:`!in` clauses, the resulting list will be equal to the product of the lengths of all diff --git a/Doc/whatsnew/2.3.rst b/Doc/whatsnew/2.3.rst index b7e4e73f4ce4aa..3d93e4257d9576 100644 --- a/Doc/whatsnew/2.3.rst +++ b/Doc/whatsnew/2.3.rst @@ -510,11 +510,11 @@ The ``getLogger(name)`` function is used to get a particular log, creating it if it doesn't exist yet. ``getLogger(None)`` returns the root logger. :: log = logging.getLogger('server') - ... + ... log.info('Listening on port %i', port) - ... + ... log.critical('Disk full') - ... + ... Log records are usually propagated up the hierarchy, so a message logged to ``server.auth`` is also seen by ``server`` and ``root``, but a :class:`~logging.Logger` diff --git a/Doc/whatsnew/3.7.rst b/Doc/whatsnew/3.7.rst index f420fa5c04479b..8d0db8c2dc0bae 100644 --- a/Doc/whatsnew/3.7.rst +++ b/Doc/whatsnew/3.7.rst @@ -717,6 +717,7 @@ include: async with srv: # some code + ... # At this point, srv is closed and no longer accepts new connections. diff --git a/Doc/whatsnew/3.8.rst b/Doc/whatsnew/3.8.rst index 7aca35b2959cd2..d1063d3397ed83 100644 --- a/Doc/whatsnew/3.8.rst +++ b/Doc/whatsnew/3.8.rst @@ -161,7 +161,7 @@ breaking client code. For example, in the :mod:`statistics` module, the parameter name *dist* may be changed in the future. This was made possible with the following function specification:: - def quantiles(dist, /, *, n=4, method='exclusive') + def quantiles(dist, /, *, n=4, method='exclusive'): ... Since the parameters to the left of ``/`` are not exposed as possible @@ -181,6 +181,7 @@ is an excerpt from code in the :mod:`collections` module:: def __init__(self, iterable=None, /, **kwds): # Note "iterable" is a possible keyword argument + ... See :pep:`570` for a full description. From ad810ffcee47f38fad3b908f2492b4c0cbfc5934 Mon Sep 17 00:00:00 2001 From: Colin Marquardt Date: Mon, 12 May 2025 18:47:42 +0200 Subject: [PATCH 2/2] Make example code more compact --- Doc/faq/programming.rst | 6 +++--- Doc/howto/ipaddress.rst | 3 +-- Doc/howto/urllib2.rst | 6 ++---- Doc/library/asyncio-eventloop.rst | 3 +-- Doc/library/asyncio-sync.rst | 12 ++++-------- Doc/library/contextlib.rst | 24 ++++++++---------------- Doc/library/inspect.rst | 3 +-- Doc/library/logging.rst | 3 +-- Doc/library/multiprocessing.rst | 6 ++---- Doc/library/sys.rst | 3 +-- Doc/library/test.rst | 22 ++++++++-------------- Doc/library/threading.rst | 9 +++------ Doc/library/weakref.rst | 3 +-- Doc/whatsnew/3.7.rst | 3 +-- Doc/whatsnew/3.8.rst | 3 +-- 15 files changed, 38 insertions(+), 71 deletions(-) diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst index ff85c737abec8e..cc768130a7568d 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -340,7 +340,7 @@ Why are default values shared between objects? This type of bug commonly bites neophyte programmers. Consider this function:: def foo(mydict={}): # Danger: shared reference to one dict for all calls - # ... compute something ... + # compute something mydict[key] = value return mydict @@ -382,8 +382,8 @@ requested again. This is called "memoizing", and can be implemented like this:: return _cache[(arg1, arg2)] # Calculate the value - result = ... # ... expensive computation ... - _cache[(arg1, arg2)] = result # Store result in the cache + result = ... # expensive computation + _cache[(arg1, arg2)] = result # Store result in the cache return result You could use a global variable containing a dictionary instead of the default diff --git a/Doc/howto/ipaddress.rst b/Doc/howto/ipaddress.rst index 5651f980f8b97c..9ff776ca9b72d3 100644 --- a/Doc/howto/ipaddress.rst +++ b/Doc/howto/ipaddress.rst @@ -254,8 +254,7 @@ It also means that network objects lend themselves to using the list membership test syntax like this:: if address in network: - # do something - ... + ... # do something Containment testing is done efficiently based on the network prefix:: diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst index 9346b5d2333d4b..efc680aebacfd5 100644 --- a/Doc/howto/urllib2.rst +++ b/Doc/howto/urllib2.rst @@ -359,8 +359,7 @@ Number 1 print('We failed to reach a server.') print('Reason: ', e.reason) else: - # everything is fine - ... + ... # everything is fine .. note:: @@ -386,8 +385,7 @@ Number 2 print('The server couldn\'t fulfill the request.') print('Error code: ', e.code) else: - # everything is fine - ... + ... # everything is fine info and geturl diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst index 15a040442caf23..a3ad6d706c94cf 100644 --- a/Doc/library/asyncio-eventloop.rst +++ b/Doc/library/asyncio-eventloop.rst @@ -1655,8 +1655,7 @@ Do not instantiate the :class:`Server` class directly. srv = await loop.create_server(...) async with srv: - # some code - ... + ... # some code # At this point, srv is closed and no longer accepts new connections. diff --git a/Doc/library/asyncio-sync.rst b/Doc/library/asyncio-sync.rst index c0e1c807b69725..3d92e609640194 100644 --- a/Doc/library/asyncio-sync.rst +++ b/Doc/library/asyncio-sync.rst @@ -51,8 +51,7 @@ Lock # ... later async with lock: - # access shared state - ... + ... # access shared state which is equivalent to:: @@ -61,8 +60,7 @@ Lock # ... later await lock.acquire() try: - # access shared state - ... + ... # access shared state finally: lock.release() @@ -301,8 +299,7 @@ Semaphore # ... later async with sem: - # work with shared resource - ... + ... # work with shared resource which is equivalent to:: @@ -311,8 +308,7 @@ Semaphore # ... later await sem.acquire() try: - # work with shared resource - ... + ... # work with shared resource finally: sem.release() diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst index 9f2c083b947400..555bfd9b2356df 100644 --- a/Doc/library/contextlib.rst +++ b/Doc/library/contextlib.rst @@ -145,8 +145,7 @@ Functions and classes provided: @timeit() async def main(): - # ... async code ... - ... + ... # async code When used as a decorator, a new generator instance is implicitly created on each function call. This allows the otherwise "one-shot" context managers @@ -242,8 +241,7 @@ Functions and classes provided: # Do not ignore any exceptions, cm has no effect. cm = contextlib.nullcontext() with cm: - # Do something - ... + ... # Do something An example using *enter_result*:: @@ -256,8 +254,7 @@ Functions and classes provided: cm = nullcontext(file_or_path) with cm as file: - # Perform processing on the file - ... + ... # Perform processing on the file It can also be used as a stand-in for :ref:`asynchronous context managers `:: @@ -271,8 +268,7 @@ Functions and classes provided: cm = nullcontext(session) async with cm as session: - # Send http requests with session - ... + ... # Send http requests with session .. versionadded:: 3.7 @@ -442,15 +438,13 @@ Functions and classes provided: def f(): with cm(): - # Do stuff - ... + ... # Do stuff ``ContextDecorator`` lets you instead write:: @cm() def f(): - # Do stuff - ... + ... # Do stuff It makes it clear that the ``cm`` applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too). @@ -712,12 +706,10 @@ protocol can be separated slightly in order to allow this:: try: x = stack.enter_context(cm) except Exception: - # handle __enter__ exception - ... + ... # handle __enter__ exception else: with stack: - # Handle normal case - ... + ... # Handle normal case Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index 7d6a5cf952e7a3..9f752c75a51d8b 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -1404,8 +1404,7 @@ is considered deprecated and may be removed in the future. def handle_stackframe_without_leak(): frame = inspect.currentframe() try: - # do something with the frame - ... + ... # do something with the frame finally: del frame diff --git a/Doc/library/logging.rst b/Doc/library/logging.rst index b28913ece7f8fc..a46895ef12c22d 100644 --- a/Doc/library/logging.rst +++ b/Doc/library/logging.rst @@ -1175,8 +1175,7 @@ functions. not undo customizations already applied by other code. For example:: class MyLogger(logging.getLoggerClass()): - # ... override behaviour here - ... + ... # override behaviour here .. function:: getLogRecordFactory() diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index 557c577d191860..89b9b0db41bc87 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -2935,8 +2935,7 @@ Explicitly pass resources to child processes from multiprocessing import Process, Lock def f(): - # ... do something using "lock" ... - ... + ... # do something using "lock" if __name__ == '__main__': lock = Lock() @@ -2948,8 +2947,7 @@ Explicitly pass resources to child processes from multiprocessing import Process, Lock def f(l): - # ... do something using "l" ... - ... + ... # do something using "l" if __name__ == '__main__': lock = Lock() diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index f2d68456ca7e4b..0855c0f4a8903f 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -1461,8 +1461,7 @@ always available. Unless explicitly noted otherwise, all variables are read-only recommended to use the following idiom:: if sys.platform.startswith('sunos'): - # SunOS-specific code here... - ... + ... # SunOS-specific code here .. versionchanged:: 3.3 On Linux, :data:`sys.platform` doesn't contain the major version anymore. diff --git a/Doc/library/test.rst b/Doc/library/test.rst index 2c5dabdcd9fe4e..c80828bd6feed6 100644 --- a/Doc/library/test.rst +++ b/Doc/library/test.rst @@ -62,30 +62,25 @@ A basic boilerplate is often used:: # Only use setUp() and tearDown() if necessary def setUp(self): - # ... code to execute in preparation for tests ... - ... + ... # code to execute in preparation for tests def tearDown(self): - # ... code to execute to clean up after tests ... - ... + ... # code to execute to clean up after tests def test_feature_one(self): # Test feature one. - # ... testing code ... - ... + ... # testing code def test_feature_two(self): # Test feature two. - # ... testing code ... - ... + ... # testing code - # ... more test methods ... + # more test methods class MyTestCase2(unittest.TestCase): - # ... same structure as MyTestCase1 ... - ... + ... # same structure as MyTestCase1 - # ... more test classes ... + # more test classes if __name__ == '__main__': unittest.main() @@ -1687,8 +1682,7 @@ The :mod:`test.support.warnings_helper` module provides support for warnings tes @warning_helper.ignore_warnings(category=DeprecationWarning) def test_suppress_warning(): - # do something - ... + ... # do something .. versionadded:: 3.8 diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst index 2352f372a21eba..b0b5cc24e36e2a 100644 --- a/Doc/library/threading.rst +++ b/Doc/library/threading.rst @@ -982,8 +982,7 @@ when they need to connect to the server:: with pool_sema: conn = connectdb() try: - # ... use connection ... - ... + ... # use connection finally: conn.close() @@ -1202,15 +1201,13 @@ entered, and ``release`` will be called when the block is exited. Hence, the following snippet:: with some_lock: - # do something... - ... + ... # do something is equivalent to:: some_lock.acquire() try: - # do something... - ... + ... # do something finally: some_lock.release() diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst index 215f38bd4f0344..36d26638af8a55 100644 --- a/Doc/library/weakref.rst +++ b/Doc/library/weakref.rst @@ -587,8 +587,7 @@ third party, such as running code when a module is unloaded:: import weakref, sys def unloading_module(): - # implicit reference to the module globals from the function body - ... + ... # implicit reference to the module globals from the function body weakref.finalize(sys.modules[__name__], unloading_module) diff --git a/Doc/whatsnew/3.7.rst b/Doc/whatsnew/3.7.rst index 8d0db8c2dc0bae..35d2f52615e43d 100644 --- a/Doc/whatsnew/3.7.rst +++ b/Doc/whatsnew/3.7.rst @@ -716,8 +716,7 @@ include: srv = await loop.create_server(...) async with srv: - # some code - ... + ... # some code # At this point, srv is closed and no longer accepts new connections. diff --git a/Doc/whatsnew/3.8.rst b/Doc/whatsnew/3.8.rst index d1063d3397ed83..fa51a409e0eb1e 100644 --- a/Doc/whatsnew/3.8.rst +++ b/Doc/whatsnew/3.8.rst @@ -180,8 +180,7 @@ is an excerpt from code in the :mod:`collections` module:: class Counter(dict): def __init__(self, iterable=None, /, **kwds): - # Note "iterable" is a possible keyword argument - ... + ... # Note "iterable" is a possible keyword argument See :pep:`570` for a full description.