Issue #23921: Standardized documentation whitespace formatting.
Original patch by James Edwards.
This commit is contained in:
parent
387235085c
commit
dba903993a
@ -577,8 +577,10 @@ other structure). ::
|
||||
class ListWrapper:
|
||||
def __init__(self, the_list):
|
||||
self.the_list = the_list
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.the_list == other.the_list
|
||||
|
||||
def __hash__(self):
|
||||
l = self.the_list
|
||||
result = 98767 - len(l)*555
|
||||
|
@ -257,7 +257,8 @@ all the threads to finish::
|
||||
import threading, time
|
||||
|
||||
def thread_task(name, n):
|
||||
for i in range(n): print(name, i)
|
||||
for i in range(n):
|
||||
print(name, i)
|
||||
|
||||
for i in range(10):
|
||||
T = threading.Thread(target=thread_task, args=(str(i), i))
|
||||
@ -273,7 +274,8 @@ A simple fix is to add a tiny sleep to the start of the run function::
|
||||
|
||||
def thread_task(name, n):
|
||||
time.sleep(0.001) # <--------------------!
|
||||
for i in range(n): print(name, i)
|
||||
for i in range(n):
|
||||
print(name, i)
|
||||
|
||||
for i in range(10):
|
||||
T = threading.Thread(target=thread_task, args=(str(i), i))
|
||||
@ -681,10 +683,10 @@ Yes. Here's a simple example that uses urllib.request::
|
||||
|
||||
import urllib.request
|
||||
|
||||
### build the query string
|
||||
# build the query string
|
||||
qs = "First=Josephine&MI=Q&Last=Public"
|
||||
|
||||
### connect and send the server a path
|
||||
# connect and send the server a path
|
||||
req = urllib.request.urlopen('http://www.some-server.out-there'
|
||||
'/cgi-bin/some-cgi-script', data=qs)
|
||||
with req:
|
||||
@ -740,8 +742,9 @@ varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
|
||||
``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's
|
||||
some sample code::
|
||||
|
||||
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
|
||||
import os
|
||||
|
||||
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
|
||||
p = os.popen("%s -t -i" % SENDMAIL, "w")
|
||||
p.write("To: receiver@example.com\n")
|
||||
p.write("Subject: test\n")
|
||||
|
@ -539,7 +539,7 @@ desired effect in a number of ways.
|
||||
args['a'] = 'new-value' # args is a mutable dictionary
|
||||
args['b'] = args['b'] + 1 # change it in-place
|
||||
|
||||
args = {'a':' old-value', 'b': 99}
|
||||
args = {'a': 'old-value', 'b': 99}
|
||||
func3(args)
|
||||
print(args['a'], args['b'])
|
||||
|
||||
@ -655,16 +655,15 @@ Essentially, assignment always binds a name to a value; The same is true of
|
||||
``def`` and ``class`` statements, but in that case the value is a
|
||||
callable. Consider the following code::
|
||||
|
||||
class A:
|
||||
pass
|
||||
|
||||
B = A
|
||||
|
||||
a = B()
|
||||
b = a
|
||||
print(b)
|
||||
>>> class A:
|
||||
... pass
|
||||
...
|
||||
>>> B = A
|
||||
>>> a = B()
|
||||
>>> b = a
|
||||
>>> print(b)
|
||||
<__main__.A object at 0x16D07CC>
|
||||
print(a)
|
||||
>>> print(a)
|
||||
<__main__.A object at 0x16D07CC>
|
||||
|
||||
Arguably the class has a name: even though it is bound to two names and invoked
|
||||
@ -1099,7 +1098,7 @@ How do I iterate over a sequence in reverse order?
|
||||
Use the :func:`reversed` built-in function, which is new in Python 2.4::
|
||||
|
||||
for x in reversed(sequence):
|
||||
... # do something with x...
|
||||
... # do something with x ...
|
||||
|
||||
This won't touch your original sequence, but build a new copy with reversed
|
||||
order to iterate over.
|
||||
@ -1107,7 +1106,7 @@ order to iterate over.
|
||||
With Python 2.3, you can use an extended slice syntax::
|
||||
|
||||
for x in sequence[::-1]:
|
||||
... # do something with x...
|
||||
... # do something with x ...
|
||||
|
||||
|
||||
How do you remove duplicates from a list?
|
||||
@ -1405,7 +1404,7 @@ A method is a function on some object ``x`` that you normally call as
|
||||
definition::
|
||||
|
||||
class C:
|
||||
def meth (self, arg):
|
||||
def meth(self, arg):
|
||||
return arg * 2 + self.attribute
|
||||
|
||||
|
||||
@ -1438,9 +1437,9 @@ that does something::
|
||||
|
||||
def search(obj):
|
||||
if isinstance(obj, Mailbox):
|
||||
# ... code to search a mailbox
|
||||
... # code to search a mailbox
|
||||
elif isinstance(obj, Document):
|
||||
# ... code to search a document
|
||||
... # code to search a document
|
||||
elif ...
|
||||
|
||||
A better approach is to define a ``search()`` method on all the classes and just
|
||||
@ -1448,11 +1447,11 @@ call it::
|
||||
|
||||
class Mailbox:
|
||||
def search(self):
|
||||
# ... code to search a mailbox
|
||||
... # code to search a mailbox
|
||||
|
||||
class Document:
|
||||
def search(self):
|
||||
# ... code to search a document
|
||||
... # code to search a document
|
||||
|
||||
obj.search()
|
||||
|
||||
@ -1509,7 +1508,7 @@ How do I call a method defined in a base class from a derived class that overrid
|
||||
Use the built-in :func:`super` function::
|
||||
|
||||
class Derived(Base):
|
||||
def meth (self):
|
||||
def meth(self):
|
||||
super(Derived, self).meth()
|
||||
|
||||
For version prior to 3.0, you may be using classic classes: For a class
|
||||
|
@ -163,9 +163,9 @@ descriptor is useful for monitoring just a few chosen attributes::
|
||||
self.val = val
|
||||
|
||||
>>> class MyClass(object):
|
||||
x = RevealAccess(10, 'var "x"')
|
||||
y = 5
|
||||
|
||||
... x = RevealAccess(10, 'var "x"')
|
||||
... y = 5
|
||||
...
|
||||
>>> m = MyClass()
|
||||
>>> m.x
|
||||
Retrieving var "x"
|
||||
@ -287,9 +287,9 @@ this::
|
||||
Running the interpreter shows how the function descriptor works in practice::
|
||||
|
||||
>>> class D(object):
|
||||
def f(self, x):
|
||||
return x
|
||||
|
||||
... def f(self, x):
|
||||
... return x
|
||||
...
|
||||
>>> d = D()
|
||||
>>> D.__dict__['f'] # Stored internally as a function
|
||||
<function f at 0x00C45070>
|
||||
@ -358,10 +358,10 @@ Since staticmethods return the underlying function with no changes, the example
|
||||
calls are unexciting::
|
||||
|
||||
>>> class E(object):
|
||||
def f(x):
|
||||
print(x)
|
||||
f = staticmethod(f)
|
||||
|
||||
... def f(x):
|
||||
... print(x)
|
||||
... f = staticmethod(f)
|
||||
...
|
||||
>>> print(E.f(3))
|
||||
3
|
||||
>>> print(E().f(3))
|
||||
@ -384,10 +384,10 @@ argument list before calling the function. This format is the same
|
||||
for whether the caller is an object or a class::
|
||||
|
||||
>>> class E(object):
|
||||
def f(klass, x):
|
||||
return klass.__name__, x
|
||||
f = classmethod(f)
|
||||
|
||||
... def f(klass, x):
|
||||
... return klass.__name__, x
|
||||
... f = classmethod(f)
|
||||
...
|
||||
>>> print(E.f(3))
|
||||
('E', 3)
|
||||
>>> print(E().f(3))
|
||||
|
@ -63,6 +63,7 @@ Here is the auxiliary module::
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
|
||||
self.logger.info('creating an instance of Auxiliary')
|
||||
|
||||
def do_something(self):
|
||||
self.logger.info('doing something')
|
||||
a = 1 + 1
|
||||
@ -793,7 +794,8 @@ the basis for code meeting your own specific requirements::
|
||||
h = logging.handlers.QueueHandler(queue) # Just the one handler needed
|
||||
root = logging.getLogger()
|
||||
root.addHandler(h)
|
||||
root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
|
||||
# send all messages, for demo; no other level or filter logic applied.
|
||||
root.setLevel(logging.DEBUG)
|
||||
|
||||
# This is the worker process top-level loop, which just logs ten events with
|
||||
# random intervening delays before terminating.
|
||||
|
@ -1115,19 +1115,19 @@ which can be either a string or a function, and the string to be processed.
|
||||
Here's a simple example of using the :meth:`sub` method. It replaces colour
|
||||
names with the word ``colour``::
|
||||
|
||||
>>> p = re.compile( '(blue|white|red)')
|
||||
>>> p.sub( 'colour', 'blue socks and red shoes')
|
||||
>>> p = re.compile('(blue|white|red)')
|
||||
>>> p.sub('colour', 'blue socks and red shoes')
|
||||
'colour socks and colour shoes'
|
||||
>>> p.sub( 'colour', 'blue socks and red shoes', count=1)
|
||||
>>> p.sub('colour', 'blue socks and red shoes', count=1)
|
||||
'colour socks and red shoes'
|
||||
|
||||
The :meth:`subn` method does the same work, but returns a 2-tuple containing the
|
||||
new string value and the number of replacements that were performed::
|
||||
|
||||
>>> p = re.compile( '(blue|white|red)')
|
||||
>>> p.subn( 'colour', 'blue socks and red shoes')
|
||||
>>> p = re.compile('(blue|white|red)')
|
||||
>>> p.subn('colour', 'blue socks and red shoes')
|
||||
('colour socks and colour shoes', 2)
|
||||
>>> p.subn( 'colour', 'no colours at all')
|
||||
>>> p.subn('colour', 'no colours at all')
|
||||
('no colours at all', 0)
|
||||
|
||||
Empty matches are replaced only when they're not adjacent to a previous match.
|
||||
|
@ -175,10 +175,10 @@ Explorer [#]_. ::
|
||||
|
||||
url = 'http://www.someserver.com/cgi-bin/register.cgi'
|
||||
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
|
||||
values = {'name' : 'Michael Foord',
|
||||
'location' : 'Northampton',
|
||||
'language' : 'Python' }
|
||||
headers = { 'User-Agent' : user_agent }
|
||||
values = {'name': 'Michael Foord',
|
||||
'location': 'Northampton',
|
||||
'language': 'Python' }
|
||||
headers = {'User-Agent': user_agent}
|
||||
|
||||
data = urllib.parse.urlencode(values)
|
||||
data = data.encode('ascii')
|
||||
|
@ -276,6 +276,6 @@ sample and subtract the whole output sample from the input sample::
|
||||
# out_test)
|
||||
prefill = '\0'*(pos+ipos)*2
|
||||
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
|
||||
outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
|
||||
outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
|
||||
return audioop.add(inputdata, outputdata, 2)
|
||||
|
||||
|
@ -225,10 +225,13 @@ The ABC supplies the remaining methods such as :meth:`__and__` and
|
||||
for value in iterable:
|
||||
if value not in lst:
|
||||
lst.append(value)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.elements)
|
||||
|
||||
def __contains__(self, value):
|
||||
return value in self.elements
|
||||
|
||||
def __len__(self):
|
||||
return len(self.elements)
|
||||
|
||||
|
@ -1029,7 +1029,7 @@ Since an ordered dictionary remembers its insertion order, it can be used
|
||||
in conjunction with sorting to make a sorted dictionary::
|
||||
|
||||
>>> # regular unsorted dictionary
|
||||
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
|
||||
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
|
||||
|
||||
>>> # dictionary sorted by key
|
||||
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
|
||||
|
@ -51,8 +51,10 @@ as they are encountered::
|
||||
class MyHTMLParser(HTMLParser):
|
||||
def handle_starttag(self, tag, attrs):
|
||||
print("Encountered a start tag:", tag)
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
print("Encountered an end tag :", tag)
|
||||
|
||||
def handle_data(self, data):
|
||||
print("Encountered some data :", data)
|
||||
|
||||
@ -237,21 +239,27 @@ examples::
|
||||
print("Start tag:", tag)
|
||||
for attr in attrs:
|
||||
print(" attr:", attr)
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
print("End tag :", tag)
|
||||
|
||||
def handle_data(self, data):
|
||||
print("Data :", data)
|
||||
|
||||
def handle_comment(self, data):
|
||||
print("Comment :", data)
|
||||
|
||||
def handle_entityref(self, name):
|
||||
c = chr(name2codepoint[name])
|
||||
print("Named ent:", c)
|
||||
|
||||
def handle_charref(self, name):
|
||||
if name.startswith('x'):
|
||||
c = chr(int(name[1:], 16))
|
||||
else:
|
||||
c = chr(int(name))
|
||||
print("Num ent :", c)
|
||||
|
||||
def handle_decl(self, data):
|
||||
print("Decl :", data)
|
||||
|
||||
@ -283,7 +291,7 @@ further parsing::
|
||||
attr: ('type', 'text/css')
|
||||
Data : #python { color: green }
|
||||
End tag : style
|
||||
>>>
|
||||
|
||||
>>> parser.feed('<script type="text/javascript">'
|
||||
... 'alert("<strong>hello!</strong>");</script>')
|
||||
Start tag: script
|
||||
|
@ -70,7 +70,7 @@ standard. However, mailcap files are supported on most Unix systems.
|
||||
An example usage::
|
||||
|
||||
>>> import mailcap
|
||||
>>> d=mailcap.getcaps()
|
||||
>>> d = mailcap.getcaps()
|
||||
>>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
|
||||
('xmpeg tmp1223', {'view': 'xmpeg %s'})
|
||||
|
||||
|
@ -25,7 +25,7 @@ GNU/POSIX syntax, and additionally generates usage and help messages for you.
|
||||
Here's an example of using :mod:`optparse` in a simple script::
|
||||
|
||||
from optparse import OptionParser
|
||||
[...]
|
||||
...
|
||||
parser = OptionParser()
|
||||
parser.add_option("-f", "--file", dest="filename",
|
||||
help="write report to FILE", metavar="FILE")
|
||||
@ -252,7 +252,7 @@ First, you need to import the OptionParser class; then, early in the main
|
||||
program, create an OptionParser instance::
|
||||
|
||||
from optparse import OptionParser
|
||||
[...]
|
||||
...
|
||||
parser = OptionParser()
|
||||
|
||||
Then you can start defining options. The basic syntax is::
|
||||
@ -718,7 +718,7 @@ you can call :func:`OptionParser.error` to signal an application-defined error
|
||||
condition::
|
||||
|
||||
(options, args) = parser.parse_args()
|
||||
[...]
|
||||
...
|
||||
if options.a and options.b:
|
||||
parser.error("options -a and -b are mutually exclusive")
|
||||
|
||||
@ -758,7 +758,7 @@ Putting it all together
|
||||
Here's what :mod:`optparse`\ -based scripts usually look like::
|
||||
|
||||
from optparse import OptionParser
|
||||
[...]
|
||||
...
|
||||
def main():
|
||||
usage = "usage: %prog [options] arg"
|
||||
parser = OptionParser(usage)
|
||||
@ -768,13 +768,13 @@ Here's what :mod:`optparse`\ -based scripts usually look like::
|
||||
action="store_true", dest="verbose")
|
||||
parser.add_option("-q", "--quiet",
|
||||
action="store_false", dest="verbose")
|
||||
[...]
|
||||
...
|
||||
(options, args) = parser.parse_args()
|
||||
if len(args) != 1:
|
||||
parser.error("incorrect number of arguments")
|
||||
if options.verbose:
|
||||
print("reading %s..." % options.filename)
|
||||
[...]
|
||||
...
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1409,7 +1409,7 @@ If you're not careful, it's easy to define options with conflicting option
|
||||
strings::
|
||||
|
||||
parser.add_option("-n", "--dry-run", ...)
|
||||
[...]
|
||||
...
|
||||
parser.add_option("-n", "--noisy", ...)
|
||||
|
||||
(This is particularly true if you've defined your own OptionParser subclass with
|
||||
@ -1450,7 +1450,7 @@ that option. If the user asks for help, the help message will reflect that::
|
||||
|
||||
Options:
|
||||
--dry-run do no harm
|
||||
[...]
|
||||
...
|
||||
-n, --noisy be noisy
|
||||
|
||||
It's possible to whittle away the option strings for a previously-added option
|
||||
@ -1465,7 +1465,7 @@ At this point, the original ``-n``/``--dry-run`` option is no longer
|
||||
accessible, so :mod:`optparse` removes it, leaving this help text::
|
||||
|
||||
Options:
|
||||
[...]
|
||||
...
|
||||
-n, --noisy be noisy
|
||||
--dry-run new dry-run option
|
||||
|
||||
@ -1701,7 +1701,7 @@ seen, but blow up if it comes after ``-b`` in the command-line. ::
|
||||
if parser.values.b:
|
||||
raise OptionValueError("can't use -a after -b")
|
||||
parser.values.a = 1
|
||||
[...]
|
||||
...
|
||||
parser.add_option("-a", action="callback", callback=check_order)
|
||||
parser.add_option("-b", action="store_true", dest="b")
|
||||
|
||||
@ -1719,7 +1719,7 @@ message and the flag that it sets must be generalized. ::
|
||||
if parser.values.b:
|
||||
raise OptionValueError("can't use %s after -b" % opt_str)
|
||||
setattr(parser.values, option.dest, 1)
|
||||
[...]
|
||||
...
|
||||
parser.add_option("-a", action="callback", callback=check_order, dest='a')
|
||||
parser.add_option("-b", action="store_true", dest="b")
|
||||
parser.add_option("-c", action="callback", callback=check_order, dest='c')
|
||||
@ -1739,7 +1739,7 @@ should not be called when the moon is full, all you have to do is this::
|
||||
raise OptionValueError("%s option invalid when moon is full"
|
||||
% opt_str)
|
||||
setattr(parser.values, option.dest, 1)
|
||||
[...]
|
||||
...
|
||||
parser.add_option("--foo",
|
||||
action="callback", callback=check_moon, dest="foo")
|
||||
|
||||
@ -1762,7 +1762,7 @@ Here's an example that just emulates the standard ``"store"`` action::
|
||||
|
||||
def store_value(option, opt_str, value, parser):
|
||||
setattr(parser.values, option.dest, value)
|
||||
[...]
|
||||
...
|
||||
parser.add_option("--foo",
|
||||
action="callback", callback=store_value,
|
||||
type="int", nargs=3, dest="foo")
|
||||
@ -1824,7 +1824,7 @@ arguments::
|
||||
del parser.rargs[:len(value)]
|
||||
setattr(parser.values, option.dest, value)
|
||||
|
||||
[...]
|
||||
...
|
||||
parser.add_option("-c", "--callback", dest="vararg_attr",
|
||||
action="callback", callback=vararg_callback)
|
||||
|
||||
|
@ -170,10 +170,11 @@ object)::
|
||||
|
||||
d[key] = data # store data at key (overwrites old data if
|
||||
# using an existing key)
|
||||
data = d[key] # retrieve a COPY of data at key (raise KeyError if no
|
||||
# such key)
|
||||
data = d[key] # retrieve a COPY of data at key (raise KeyError
|
||||
# if no such key)
|
||||
del d[key] # delete data stored at key (raises KeyError
|
||||
# if no such key)
|
||||
|
||||
flag = key in d # true if the key exists
|
||||
klist = list(d.keys()) # a list of all existing keys (slow!)
|
||||
|
||||
|
@ -252,10 +252,12 @@ Additional Utility Classes and Functions
|
||||
class SimpleNamespace:
|
||||
def __init__(self, **kwargs):
|
||||
self.__dict__.update(kwargs)
|
||||
|
||||
def __repr__(self):
|
||||
keys = sorted(self.__dict__)
|
||||
items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
|
||||
return "{}({})".format(type(self).__name__, ", ".join(items))
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__dict__ == other.__dict__
|
||||
|
||||
|
@ -1174,7 +1174,7 @@ The code for the sample CGI used in the above example is::
|
||||
Here is an example of doing a ``PUT`` request using :class:`Request`::
|
||||
|
||||
import urllib.request
|
||||
DATA=b'some data'
|
||||
DATA = b'some data'
|
||||
req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
|
||||
with urllib.request.urlopen(req) as f:
|
||||
pass
|
||||
|
@ -216,7 +216,7 @@ A working example follows. The server code::
|
||||
from xmlrpc.server import SimpleXMLRPCServer
|
||||
|
||||
def is_even(n):
|
||||
return n%2 == 0
|
||||
return n % 2 == 0
|
||||
|
||||
server = SimpleXMLRPCServer(("localhost", 8000))
|
||||
print("Listening on port 8000...")
|
||||
@ -373,7 +373,7 @@ returning a complex type object. The server code::
|
||||
|
||||
# A marshalling error is going to occur because we're returning a
|
||||
# complex number
|
||||
def add(x,y):
|
||||
def add(x, y):
|
||||
return x+y+0j
|
||||
|
||||
server = SimpleXMLRPCServer(("localhost", 8000))
|
||||
@ -566,12 +566,15 @@ transport. The following example shows how:
|
||||
class ProxiedTransport(xmlrpc.client.Transport):
|
||||
def set_proxy(self, proxy):
|
||||
self.proxy = proxy
|
||||
|
||||
def make_connection(self, host):
|
||||
self.realhost = host
|
||||
h = http.client.HTTPConnection(self.proxy)
|
||||
return h
|
||||
|
||||
def send_request(self, connection, handler, request_body, debug):
|
||||
connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
|
||||
|
||||
def send_host(self, connection, host):
|
||||
connection.putheader('Host', self.realhost)
|
||||
|
||||
|
@ -162,12 +162,15 @@ binding::
|
||||
def scope_test():
|
||||
def do_local():
|
||||
spam = "local spam"
|
||||
|
||||
def do_nonlocal():
|
||||
nonlocal spam
|
||||
spam = "nonlocal spam"
|
||||
|
||||
def do_global():
|
||||
global spam
|
||||
spam = "global spam"
|
||||
|
||||
spam = "test spam"
|
||||
do_local()
|
||||
print("After local assignment:", spam)
|
||||
@ -260,6 +263,7 @@ definition looked like this::
|
||||
class MyClass:
|
||||
"""A simple example class"""
|
||||
i = 12345
|
||||
|
||||
def f(self):
|
||||
return 'hello world'
|
||||
|
||||
@ -508,8 +512,10 @@ variable in the class is also ok. For example::
|
||||
|
||||
class C:
|
||||
f = f1
|
||||
|
||||
def g(self):
|
||||
return 'hello world'
|
||||
|
||||
h = g
|
||||
|
||||
Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to
|
||||
@ -523,8 +529,10 @@ argument::
|
||||
class Bag:
|
||||
def __init__(self):
|
||||
self.data = []
|
||||
|
||||
def add(self, x):
|
||||
self.data.append(x)
|
||||
|
||||
def addtwice(self, x):
|
||||
self.add(x)
|
||||
self.add(x)
|
||||
@ -839,8 +847,10 @@ defines :meth:`__next__`, then :meth:`__iter__` can just return ``self``::
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
self.index = len(data)
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self.index == 0:
|
||||
raise StopIteration
|
||||
|
@ -232,7 +232,7 @@ If you want to concatenate variables or a variable and a literal, use ``+``::
|
||||
This feature is particularly useful when you want to break long strings::
|
||||
|
||||
>>> text = ('Put several strings within parentheses '
|
||||
'to have them joined together.')
|
||||
... 'to have them joined together.')
|
||||
>>> text
|
||||
'Put several strings within parentheses to have them joined together.'
|
||||
|
||||
|
@ -180,6 +180,7 @@ tasks in background while the main program continues to run::
|
||||
threading.Thread.__init__(self)
|
||||
self.infile = infile
|
||||
self.outfile = outfile
|
||||
|
||||
def run(self):
|
||||
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
|
||||
f.write(self.infile)
|
||||
|
@ -212,7 +212,8 @@ loaded and called with code like this::
|
||||
|
||||
>>> import json, logging.config
|
||||
>>> with open('conf.json') as f:
|
||||
conf = json.load(f)
|
||||
... conf = json.load(f)
|
||||
...
|
||||
>>> logging.config.dictConfig(conf)
|
||||
>>> logging.info("Transaction completed normally")
|
||||
INFO : root : Transaction completed normally
|
||||
@ -460,15 +461,15 @@ Some smaller changes made to the core Python language are:
|
||||
'The testing project status is green as of February 15, 2011'
|
||||
|
||||
>>> class LowerCasedDict(dict):
|
||||
def __getitem__(self, key):
|
||||
return dict.__getitem__(self, key.lower())
|
||||
... def __getitem__(self, key):
|
||||
... return dict.__getitem__(self, key.lower())
|
||||
>>> lcd = LowerCasedDict(part='widgets', quantity=10)
|
||||
>>> 'There are {QUANTITY} {Part} in stock'.format_map(lcd)
|
||||
'There are 10 widgets in stock'
|
||||
|
||||
>>> class PlaceholderDict(dict):
|
||||
def __missing__(self, key):
|
||||
return '<{}>'.format(key)
|
||||
... def __missing__(self, key):
|
||||
... return '<{}>'.format(key)
|
||||
>>> 'Hello {name}, welcome to {location}'.format_map(PlaceholderDict())
|
||||
'Hello <name>, welcome to <location>'
|
||||
|
||||
@ -496,10 +497,10 @@ Some smaller changes made to the core Python language are:
|
||||
exceptions pass through::
|
||||
|
||||
>>> class A:
|
||||
@property
|
||||
def f(self):
|
||||
return 1 // 0
|
||||
|
||||
... @property
|
||||
... def f(self):
|
||||
... return 1 // 0
|
||||
...
|
||||
>>> a = A()
|
||||
>>> hasattr(a, 'f')
|
||||
Traceback (most recent call last):
|
||||
@ -799,6 +800,7 @@ functools
|
||||
def __eq__(self, other):
|
||||
return ((self.lastname.lower(), self.firstname.lower()) ==
|
||||
(other.lastname.lower(), other.firstname.lower()))
|
||||
|
||||
def __lt__(self, other):
|
||||
return ((self.lastname.lower(), self.firstname.lower()) <
|
||||
(other.lastname.lower(), other.firstname.lower()))
|
||||
@ -942,7 +944,7 @@ released and a :exc:`~threading.BrokenBarrierError` exception is raised::
|
||||
def get_votes(site):
|
||||
ballots = conduct_election(site)
|
||||
try:
|
||||
all_polls_closed.wait(timeout = midnight - time.now())
|
||||
all_polls_closed.wait(timeout=midnight - time.now())
|
||||
except BrokenBarrierError:
|
||||
lockbox = seal_ballots(ballots)
|
||||
queue.put(lockbox)
|
||||
@ -1097,16 +1099,16 @@ for slice notation are well-suited to in-place editing::
|
||||
>>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11
|
||||
|
||||
>>> def change_location(buffer, record_number, location):
|
||||
start = record_number * REC_LEN + LOC_START
|
||||
buffer[start: start+LOC_LEN] = location
|
||||
... start = record_number * REC_LEN + LOC_START
|
||||
... buffer[start: start+LOC_LEN] = location
|
||||
|
||||
>>> import io
|
||||
|
||||
>>> byte_stream = io.BytesIO(
|
||||
b'G3805 storeroom Main chassis '
|
||||
b'X7899 shipping Reserve cog '
|
||||
b'L6988 receiving Primary sprocket'
|
||||
)
|
||||
... b'G3805 storeroom Main chassis '
|
||||
... b'X7899 shipping Reserve cog '
|
||||
... b'L6988 receiving Primary sprocket'
|
||||
... )
|
||||
>>> buffer = byte_stream.getbuffer()
|
||||
>>> change_location(buffer, 1, b'warehouse ')
|
||||
>>> change_location(buffer, 0, b'showroom ')
|
||||
@ -1131,10 +1133,10 @@ decorator, :func:`~reprlib.recursive_repr`, for detecting recursive calls to
|
||||
:meth:`__repr__` and substituting a placeholder string instead::
|
||||
|
||||
>>> class MyList(list):
|
||||
@recursive_repr()
|
||||
def __repr__(self):
|
||||
return '<' + '|'.join(map(repr, self)) + '>'
|
||||
|
||||
... @recursive_repr()
|
||||
... def __repr__(self):
|
||||
... return '<' + '|'.join(map(repr, self)) + '>'
|
||||
...
|
||||
>>> m = MyList('abc')
|
||||
>>> m.append(m)
|
||||
>>> m.append('x')
|
||||
@ -1197,8 +1199,8 @@ the field names::
|
||||
>>> w.writeheader()
|
||||
"name","dept"
|
||||
>>> w.writerows([
|
||||
{'name': 'tom', 'dept': 'accounting'},
|
||||
{'name': 'susan', 'dept': 'Salesl'}])
|
||||
... {'name': 'tom', 'dept': 'accounting'},
|
||||
... {'name': 'susan', 'dept': 'Salesl'}])
|
||||
"tom","accounting"
|
||||
"susan","sales"
|
||||
|
||||
@ -1423,14 +1425,14 @@ function can return *None*::
|
||||
>>> import tarfile, glob
|
||||
|
||||
>>> def myfilter(tarinfo):
|
||||
if tarinfo.isfile(): # only save real files
|
||||
tarinfo.uname = 'monty' # redact the user name
|
||||
return tarinfo
|
||||
... if tarinfo.isfile(): # only save real files
|
||||
... tarinfo.uname = 'monty' # redact the user name
|
||||
... return tarinfo
|
||||
|
||||
>>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:
|
||||
for filename in glob.glob('*.txt'):
|
||||
tf.add(filename, filter=myfilter)
|
||||
tf.list()
|
||||
... for filename in glob.glob('*.txt'):
|
||||
... tf.add(filename, filter=myfilter)
|
||||
... tf.list()
|
||||
-rw-r--r-- monty/501 902 2011-01-26 17:59:11 annotations.txt
|
||||
-rw-r--r-- monty/501 123 2011-01-26 17:59:11 general_questions.txt
|
||||
-rw-r--r-- monty/501 3514 2011-01-26 17:59:11 prion.txt
|
||||
@ -1538,7 +1540,7 @@ step is non-destructive (the original files are left unchanged).
|
||||
|
||||
>>> os.chdir('mydata') # change to the source directory
|
||||
>>> f = shutil.make_archive('/var/backup/mydata',
|
||||
'zip') # archive the current directory
|
||||
... 'zip') # archive the current directory
|
||||
>>> f # show the name of archive
|
||||
'/var/backup/mydata.zip'
|
||||
>>> os.chdir('tmp') # change to an unpacking
|
||||
@ -1551,11 +1553,11 @@ step is non-destructive (the original files are left unchanged).
|
||||
('zip', 'ZIP file')]
|
||||
|
||||
>>> shutil.register_archive_format( # register a new archive format
|
||||
name = 'xz',
|
||||
function = xz.compress, # callable archiving function
|
||||
extra_args = [('level', 8)], # arguments to the function
|
||||
description = 'xz compression'
|
||||
)
|
||||
... name='xz',
|
||||
... function=xz.compress, # callable archiving function
|
||||
... extra_args=[('level', 8)], # arguments to the function
|
||||
... description='xz compression'
|
||||
... )
|
||||
|
||||
(Contributed by Tarek Ziadé.)
|
||||
|
||||
@ -1854,7 +1856,7 @@ inspect
|
||||
|
||||
>>> from inspect import getgeneratorstate
|
||||
>>> def gen():
|
||||
yield 'demo'
|
||||
... yield 'demo'
|
||||
>>> g = gen()
|
||||
>>> getgeneratorstate(g)
|
||||
'GEN_CREATED'
|
||||
@ -1874,11 +1876,11 @@ inspect
|
||||
change state while it is searching::
|
||||
|
||||
>>> class A:
|
||||
@property
|
||||
def f(self):
|
||||
print('Running')
|
||||
return 10
|
||||
|
||||
... @property
|
||||
... def f(self):
|
||||
... print('Running')
|
||||
... return 10
|
||||
...
|
||||
>>> a = A()
|
||||
>>> getattr(a, 'f')
|
||||
Running
|
||||
@ -2102,19 +2104,19 @@ Config parsers gained a new API based on the mapping protocol::
|
||||
|
||||
>>> parser = ConfigParser()
|
||||
>>> parser.read_string("""
|
||||
[DEFAULT]
|
||||
location = upper left
|
||||
visible = yes
|
||||
editable = no
|
||||
color = blue
|
||||
|
||||
[main]
|
||||
title = Main Menu
|
||||
color = green
|
||||
|
||||
[options]
|
||||
title = Options
|
||||
""")
|
||||
... [DEFAULT]
|
||||
... location = upper left
|
||||
... visible = yes
|
||||
... editable = no
|
||||
... color = blue
|
||||
...
|
||||
... [main]
|
||||
... title = Main Menu
|
||||
... color = green
|
||||
...
|
||||
... [options]
|
||||
... title = Options
|
||||
... """)
|
||||
>>> parser['main']['color']
|
||||
'green'
|
||||
>>> parser['main']['editable']
|
||||
@ -2138,24 +2140,24 @@ handler :class:`~configparser.ExtendedInterpolation`::
|
||||
|
||||
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
|
||||
>>> parser.read_dict({'buildout': {'directory': '/home/ambv/zope9'},
|
||||
'custom': {'prefix': '/usr/local'}})
|
||||
... 'custom': {'prefix': '/usr/local'}})
|
||||
>>> parser.read_string("""
|
||||
[buildout]
|
||||
parts =
|
||||
zope9
|
||||
instance
|
||||
find-links =
|
||||
${buildout:directory}/downloads/dist
|
||||
|
||||
[zope9]
|
||||
recipe = plone.recipe.zope9install
|
||||
location = /opt/zope
|
||||
|
||||
[instance]
|
||||
recipe = plone.recipe.zope9instance
|
||||
zope9-location = ${zope9:location}
|
||||
zope-conf = ${custom:prefix}/etc/zope.conf
|
||||
""")
|
||||
... [buildout]
|
||||
... parts =
|
||||
... zope9
|
||||
... instance
|
||||
... find-links =
|
||||
... ${buildout:directory}/downloads/dist
|
||||
...
|
||||
... [zope9]
|
||||
... recipe = plone.recipe.zope9install
|
||||
... location = /opt/zope
|
||||
...
|
||||
... [instance]
|
||||
... recipe = plone.recipe.zope9instance
|
||||
... zope9-location = ${zope9:location}
|
||||
... zope-conf = ${custom:prefix}/etc/zope.conf
|
||||
... """)
|
||||
>>> parser['buildout']['find-links']
|
||||
'\n/home/ambv/zope9/downloads/dist'
|
||||
>>> parser['instance']['zope-conf']
|
||||
@ -2207,9 +2209,9 @@ string, then the *safe*, *encoding*, and *error* parameters are sent to
|
||||
:func:`~urllib.parse.quote_plus` for encoding::
|
||||
|
||||
>>> urllib.parse.urlencode([
|
||||
('type', 'telenovela'),
|
||||
('name', '¿Dónde Está Elisa?')],
|
||||
encoding='latin-1')
|
||||
... ('type', 'telenovela'),
|
||||
... ('name', '¿Dónde Está Elisa?')],
|
||||
... encoding='latin-1')
|
||||
'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'
|
||||
|
||||
As detailed in :ref:`parsing-ascii-encoded-bytes`, all the :mod:`urllib.parse`
|
||||
|
@ -746,7 +746,7 @@ optional *current_offset*), and the resulting object can be iterated to produce
|
||||
method, equivalent to calling :mod:`~dis.dis` on the constructor argument, but
|
||||
returned as a multi-line string::
|
||||
|
||||
>>> bytecode = dis.Bytecode(lambda x: x +1, current_offset=3)
|
||||
>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
|
||||
>>> for instr in bytecode:
|
||||
... print('{} ({})'.format(instr.opname, instr.opcode))
|
||||
LOAD_FAST (124)
|
||||
|
Loading…
x
Reference in New Issue
Block a user