Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6f0d59b

Browse files
committed
Beautify code examples.
1 parent 66352d2 commit 6f0d59b

1 file changed

Lines changed: 80 additions & 80 deletions

File tree

Doc/whatsnew/3.2.rst

Lines changed: 80 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -208,10 +208,10 @@ dictionary::
208208
If that dictionary is stored in a file called :file:`conf.json`, it can be
209209
loaded and called with code like this::
210210

211-
>>> import logging.config
212-
>>> logging.config.dictConfig(json.load(open('conf.json', 'rb')))
213-
>>> logging.info("Transaction completed normally")
214-
>>> logging.critical("Abnormal termination")
211+
import logging.config
212+
logging.config.dictConfig(json.load(open('conf.json', 'rb')))
213+
logging.info("Transaction completed normally")
214+
logging.critical("Abnormal termination")
215215

216216
.. seealso::
217217

@@ -482,24 +482,24 @@ Some smaller changes made to the core Python language are:
482482
* Previously it was illegal to delete a name from the local namespace if it
483483
occurs as a free variable in a nested block::
484484

485-
>>> def outer(x):
486-
... def inner():
487-
... return x
488-
... inner()
489-
... del x
485+
def outer(x):
486+
def inner():
487+
return x
488+
inner()
489+
del x
490490

491491
This is now allowed. Remember that the target of an :keyword:`except` clause
492492
is cleared, so this code which used to work with Python 2.6, raised a
493493
:exc:`SyntaxError` with Python 3.1 and now works again::
494494

495-
>>> def f():
496-
... def print_error():
497-
... print(e)
498-
... try:
499-
... something
500-
... except Exception as e:
501-
... print_error()
502-
... # implicit "del e" here
495+
def f():
496+
def print_error():
497+
print(e)
498+
try:
499+
something
500+
except Exception as e:
501+
print_error()
502+
# implicit "del e" here
503503

504504
(See :issue:`4617`.)
505505

@@ -598,7 +598,7 @@ Another significant win is the addition of substantially better support for
598598
*SSL* connections and security certificates.
599599

600600
In addition, more classes now implement a :term:`context manager` to support
601-
convenient and reliable resource clean-up using the :keyword:`with`-statement.
601+
convenient and reliable resource clean-up using the :keyword:`with` statement.
602602

603603
email
604604
-----
@@ -682,16 +682,16 @@ functools
682682
resource whenever the results are expected to be the same.
683683

684684
For example, adding a caching decorator to a database query function can save
685-
database accesses for popular searches::
685+
database accesses for popular searches:
686686

687-
@functools.lru_cache(maxsize=300)
688-
def get_phone_number(name):
689-
c = conn.cursor()
690-
c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
691-
return c.fetchone()[0]
687+
>>> @functools.lru_cache(maxsize=300)
688+
>>> def get_phone_number(name):
689+
c = conn.cursor()
690+
c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
691+
return c.fetchone()[0]
692692

693693
>>> for name in user_requests:
694-
... get_phone_number(name) # cached lookup
694+
get_phone_number(name) # cached lookup
695695

696696
To help with choosing an effective cache size, the wrapped function is
697697
instrumented for tracking cache statistics:
@@ -928,40 +928,40 @@ both roles.
928928

929929
The basic idea is that both context managers and function decorators can be used
930930
for pre-action and post-action wrappers. Context managers wrap a group of
931-
statements using the :keyword:`with`-statement, and function decorators wrap a
931+
statements using the :keyword:`with` statement, and function decorators wrap a
932932
group of statements enclosed in a function. So, occasionally there is a need to
933933
write a pre-action or post-action wrapper that can be used in either role.
934934

935935
For example, it is sometimes useful to wrap functions or groups of statements
936936
with a logger that can track the time of entry and time of exit. Rather than
937937
writing both a function decorator and a context manager for the task, the
938938
:func:`~contextlib.contextmanager` provides both capabilities in a single
939-
definition:
939+
definition::
940940

941-
>>> import logging
942-
>>> logging.basicConfig(level=logging.INFO)
943-
>>> @contextmanager
944-
... def track_entry_and_exit(name):
945-
... logging.info('Entering: {}'.format(name))
946-
... yield
947-
... logging.info('Exiting: {}'.format(name))
941+
import logging
942+
logging.basicConfig(level=logging.INFO)
943+
@contextmanager
944+
def track_entry_and_exit(name):
945+
logging.info('Entering: {}'.format(name))
946+
yield
947+
logging.info('Exiting: {}'.format(name))
948948

949-
Formerly, this would have only been usable as a context manager:
949+
Formerly, this would have only been usable as a context manager::
950950

951-
>>> with track_entry_and_exit('widget loader'):
952-
... print('Some time consuming activity goes here')
953-
... load_widget()
951+
with track_entry_and_exit('widget loader'):
952+
print('Some time consuming activity goes here')
953+
load_widget()
954954

955-
Now, it can be used as a decorator as well:
955+
Now, it can be used as a decorator as well::
956956

957-
>>> @track_entry_and_exit('widget loader')
958-
... def activity():
959-
... print('Some time consuming activity goes here')
960-
... load_widget()
957+
@track_entry_and_exit('widget loader')
958+
def activity():
959+
print('Some time consuming activity goes here')
960+
load_widget()
961961

962962
Trying to fulfill two roles at once places some limitations on the technique.
963963
Context managers normally have the flexibility to return an argument usable by
964-
the :keyword:`with`-statement, but there is no parallel for function decorators.
964+
the :keyword:`with` statement, but there is no parallel for function decorators.
965965

966966
In the above example, there is not a clean way for the *track_entry_and_exit*
967967
context manager to return a logging instance for use in the body of enclosed
@@ -976,8 +976,8 @@ Mark Dickinson crafted an elegant and efficient scheme for assuring that
976976
different numeric datatypes will have the same hash value whenever their actual
977977
values are equal (:issue:`8188`)::
978978

979-
>>> assert hash(Fraction(3, 2)) == hash(1.5) == \
980-
hash(Decimal("1.5")) == hash(complex(1.5, 0))
979+
assert hash(Fraction(3, 2)) == hash(1.5) == \
980+
hash(Decimal("1.5")) == hash(complex(1.5, 0))
981981

982982
An early decision to limit the inter-operability of various numeric types has
983983
been relaxed. It is still unsupported (and ill-advised) to to have implicit
@@ -1235,10 +1235,10 @@ names.
12351235
* The :mod:`unittest` module has two new methods,
12361236
:meth:`~unittest.TestCase.assertWarns` and
12371237
:meth:`~unittest.TestCase.assertWarnsRegex` to verify that a given warning type
1238-
is triggered by the code under test:
1238+
is triggered by the code under test::
12391239

1240-
>>> with self.assertWarns(DeprecationWarning):
1241-
... legacy_function('XYZ')
1240+
with self.assertWarns(DeprecationWarning):
1241+
legacy_function('XYZ')
12421242

12431243
(Contributed by Antoine Pitrou, :issue:`9754`.)
12441244

@@ -1331,10 +1331,10 @@ tempfile
13311331

13321332
The :mod:`tempfile` module has a new context manager,
13331333
:class:`~tempfile.TemporaryDirectory` which provides easy deterministic
1334-
cleanup of temporary directories:
1334+
cleanup of temporary directories::
13351335

1336-
>>> with tempfile.TemporaryDirectory() as tmpdirname:
1337-
... print('created temporary dir:', tmpdirname)
1336+
with tempfile.TemporaryDirectory() as tmpdirname:
1337+
print('created temporary dir:', tmpdirname)
13381338

13391339
(Contributed by Neil Schemenauer and Nick Coghlan; :issue:`5178`.)
13401340

@@ -1456,13 +1456,13 @@ Config parsers gained a new API based on the mapping protocol::
14561456

14571457
>>> parser = ConfigParser()
14581458
>>> parser.read_string("""
1459-
... [DEFAULT]
1460-
... monty = python
1461-
...
1462-
... [phrases]
1463-
... the = who
1464-
... full = metal jacket
1465-
... """)
1459+
[DEFAULT]
1460+
monty = python
1461+
1462+
[phrases]
1463+
the = who
1464+
full = metal jacket
1465+
""")
14661466
>>> parser['phrases']['full']
14671467
'metal jacket'
14681468
>>> section = parser['phrases']
@@ -1485,24 +1485,24 @@ support for pluggable interpolation, an additional interpolation handler
14851485

14861486
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
14871487
>>> parser.read_dict({'buildout': {'directory': '/home/ambv/zope9'},
1488-
... 'custom': {'prefix': '/usr/local'}})
1488+
'custom': {'prefix': '/usr/local'}})
14891489
>>> parser.read_string("""
1490-
... [buildout]
1491-
... parts =
1492-
... zope9
1493-
... instance
1494-
... find-links =
1495-
... ${buildout:directory}/downloads/dist
1496-
...
1497-
... [zope9]
1498-
... recipe = plone.recipe.zope9install
1499-
... location = /opt/zope
1500-
...
1501-
... [instance]
1502-
... recipe = plone.recipe.zope9instance
1503-
... zope9-location = ${zope9:location}
1504-
... zope-conf = ${custom:prefix}/etc/zope.conf
1505-
... """)
1490+
[buildout]
1491+
parts =
1492+
zope9
1493+
instance
1494+
find-links =
1495+
${buildout:directory}/downloads/dist
1496+
1497+
[zope9]
1498+
recipe = plone.recipe.zope9install
1499+
location = /opt/zope
1500+
1501+
[instance]
1502+
recipe = plone.recipe.zope9instance
1503+
zope9-location = ${zope9:location}
1504+
zope-conf = ${custom:prefix}/etc/zope.conf
1505+
""")
15061506
>>> parser['buildout']['find-links']
15071507
'\n/home/ambv/zope9/downloads/dist'
15081508
>>> parser['instance']['zope-conf']
@@ -1876,10 +1876,10 @@ require changes to your code:
18761876
and it does a better job finalizing multiple context managers when one of them
18771877
raises an exception::
18781878

1879-
>>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
1880-
... for line in infile:
1881-
... if '<critical>' in line:
1882-
... outfile.write(line)
1879+
with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
1880+
for line in infile:
1881+
if '<critical>' in line:
1882+
outfile.write(line)
18831883

18841884
(Contributed by Georg Brandl and Mattias Brändström;
18851885
`appspot issue 53094 <http://codereview.appspot.com/53094>`_.)

0 commit comments

Comments
 (0)