Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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
Loading
from
Open
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 5 additions & 4 deletions 9 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,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
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
2 changes: 1 addition & 1 deletion 2 Doc/howto/ipaddress.rst
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +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::

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


.. note::
Expand All @@ -385,7 +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
Expand Down
2 changes: 1 addition & 1 deletion 2 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 2 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
2 changes: 1 addition & 1 deletion 2 Doc/library/asyncio-eventloop.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1655,7 +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.

Expand Down
8 changes: 4 additions & 4 deletions 8 Doc/library/asyncio-sync.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Lock

# ... later
async with lock:
# access shared state
... # access shared state

which is equivalent to::

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

Expand Down Expand Up @@ -299,7 +299,7 @@ Semaphore

# ... later
async with sem:
# work with shared resource
... # work with shared resource

which is equivalent to::

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

Expand Down
17 changes: 9 additions & 8 deletions 17 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 @@ -144,7 +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
Expand Down Expand Up @@ -240,7 +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*::

Expand All @@ -253,7 +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 <async-context-managers>`::
Expand All @@ -267,7 +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

Expand Down Expand Up @@ -437,13 +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).
Expand Down Expand Up @@ -705,10 +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
Expand Down
3 changes: 3 additions & 0 deletions 3 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 4 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 2 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
2 changes: 1 addition & 1 deletion 2 Doc/library/inspect.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1404,7 +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

Expand Down
2 changes: 1 addition & 1 deletion 2 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
2 changes: 1 addition & 1 deletion 2 Doc/library/logging.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1175,7 +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()
Expand Down
4 changes: 2 additions & 2 deletions 4 Doc/library/multiprocessing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2935,7 +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()
Expand All @@ -2947,7 +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()
Expand Down
2 changes: 1 addition & 1 deletion 2 Doc/library/sys.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1461,7 +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.
Expand Down
16 changes: 8 additions & 8 deletions 16 Doc/library/test.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,25 +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()
Expand Down Expand Up @@ -1682,7 +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

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

Expand Down Expand Up @@ -1201,13 +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()

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


Expand Down
Loading
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.