Skip to content

gh-133905: Fix parsing problems in example code #133906

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Doc/faq/programming.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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::
Expand Down
1 change: 1 addition & 0 deletions Doc/howto/ipaddress.rst
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ membership test syntax like this::

if address in network:
# do something
...
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer a single line here and for most of the examples. Could do the revision with sed.

Suggested change
# do something
...
... # do something

Copy link
Contributor Author

@cmarqu cmarqu May 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, there was indeed one such occurrence left, fixed. A follow-up PR could reformat all the examples consistently; this PR only works on the places where there were parsing problems.


Containment testing is done efficiently based on the network prefix::

Expand Down
2 changes: 1 addition & 1 deletion Doc/howto/logging.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions Doc/howto/urllib2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,7 @@ Number 1
print('Reason: ', e.reason)
else:
# everything is fine
...


.. note::
Expand All @@ -386,6 +387,7 @@ Number 2
print('Error code: ', e.code)
else:
# everything is fine
...


info and geturl
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/ast.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

.. testsetup::

import ast
import ast

**Source code:** :source:`Lib/ast.py`

Expand Down
1 change: 1 addition & 0 deletions Doc/library/asyncio-eventloop.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 4 additions & 0 deletions Doc/library/asyncio-sync.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Lock
# ... later
async with lock:
# access shared state
...

which is equivalent to::

Expand All @@ -61,6 +62,7 @@ Lock
await lock.acquire()
try:
# access shared state
...
finally:
lock.release()

Expand Down Expand Up @@ -300,6 +302,7 @@ Semaphore
# ... later
async with sem:
# work with shared resource
...

which is equivalent to::

Expand All @@ -309,6 +312,7 @@ Semaphore
await sem.acquire()
try:
# work with shared resource
...
finally:
sem.release()

Expand Down
9 changes: 9 additions & 0 deletions Doc/library/contextlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -241,6 +243,7 @@ Functions and classes provided:
cm = contextlib.nullcontext()
with cm:
# Do something
...

An example using *enter_result*::

Expand All @@ -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 <async-context-managers>`::
Expand All @@ -268,6 +272,7 @@ Functions and classes provided:

async with cm as session:
# Send http requests with session
...

.. versionadded:: 3.7

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions Doc/library/dataclasses.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__`
-----------------------------------------------------------
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions Doc/library/decimal.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1903,7 +1903,7 @@ threads calling :func:`getcontext`. For example::
t1.start()
t2.start()
t3.start()
. . .
...

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/dis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions Doc/library/inspect.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion Doc/library/logging.config.rst
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ following configuration::
'bar' : 'baz',
'spam' : 99.9,
'answer' : 42,
'.' {
'.' : {
'foo': 'bar',
'baz': 'bozz'
}
Expand Down
1 change: 1 addition & 0 deletions Doc/library/logging.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,7 @@ functions.

class MyLogger(logging.getLoggerClass()):
# ... override behaviour here
...


.. function:: getLogRecordFactory()
Expand Down
6 changes: 4 additions & 2 deletions Doc/library/multiprocessing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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()
Expand Down
1 change: 1 addition & 0 deletions Doc/library/sys.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 13 additions & 7 deletions Doc/library/test.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions Doc/library/threading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,7 @@ when they need to connect to the server::
conn = connectdb()
try:
# ... use connection ...
...
finally:
conn.close()

Expand Down Expand Up @@ -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()

Expand Down
1 change: 1 addition & 0 deletions Doc/library/tkinter.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion Doc/library/urllib.request.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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')
...
Expand Down
1 change: 1 addition & 0 deletions Doc/library/weakref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
1 change: 1 addition & 0 deletions Doc/tutorial/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions Doc/tutorial/controlflow.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
Loading
Loading