Commit 12d547a8 authored by Serhiy Storchaka's avatar Serhiy Storchaka

Issue #23921: Standardized documentation whitespace formatting.

Original patch by James Edwards.
parent 09f1679a
...@@ -625,8 +625,10 @@ other structure). :: ...@@ -625,8 +625,10 @@ other structure). ::
class ListWrapper: class ListWrapper:
def __init__(self, the_list): def __init__(self, the_list):
self.the_list = the_list self.the_list = the_list
def __eq__(self, other): def __eq__(self, other):
return self.the_list == other.the_list return self.the_list == other.the_list
def __hash__(self): def __hash__(self):
l = self.the_list l = self.the_list
result = 98767 - len(l)*555 result = 98767 - len(l)*555
......
...@@ -658,20 +658,20 @@ Yes. Here's a simple example that uses httplib:: ...@@ -658,20 +658,20 @@ Yes. Here's a simple example that uses httplib::
import httplib, sys, time import httplib, sys, time
### build the query string # build the query string
qs = "First=Josephine&MI=Q&Last=Public" qs = "First=Josephine&MI=Q&Last=Public"
### connect and send the server a path # connect and send the server a path
httpobj = httplib.HTTP('www.some-server.out-there', 80) httpobj = httplib.HTTP('www.some-server.out-there', 80)
httpobj.putrequest('POST', '/cgi-bin/some-cgi-script') httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
### now generate the rest of the HTTP headers... # now generate the rest of the HTTP headers...
httpobj.putheader('Accept', '*/*') httpobj.putheader('Accept', '*/*')
httpobj.putheader('Connection', 'Keep-Alive') httpobj.putheader('Connection', 'Keep-Alive')
httpobj.putheader('Content-type', 'application/x-www-form-urlencoded') httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
httpobj.putheader('Content-length', '%d' % len(qs)) httpobj.putheader('Content-length', '%d' % len(qs))
httpobj.endheaders() httpobj.endheaders()
httpobj.send(qs) httpobj.send(qs)
### find out what the server said in response... # find out what the server said in response...
reply, msg, hdrs = httpobj.getreply() reply, msg, hdrs = httpobj.getreply()
if reply != 200: if reply != 200:
sys.stdout.write(httpobj.getfile().read()) sys.stdout.write(httpobj.getfile().read())
...@@ -724,8 +724,9 @@ varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes ...@@ -724,8 +724,9 @@ varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's ``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's
some sample code:: some sample code::
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
import os import os
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t -i" % SENDMAIL, "w") p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@example.com\n") p.write("To: receiver@example.com\n")
p.write("Subject: test\n") p.write("Subject: test\n")
......
...@@ -699,7 +699,7 @@ desired effect in a number of ways. ...@@ -699,7 +699,7 @@ desired effect in a number of ways.
args['a'] = 'new-value' # args is a mutable dictionary args['a'] = 'new-value' # args is a mutable dictionary
args['b'] = args['b'] + 1 # change it in-place args['b'] = args['b'] + 1 # change it in-place
args = {'a':' old-value', 'b': 99} args = {'a': 'old-value', 'b': 99}
func3(args) func3(args)
print args['a'], args['b'] print args['a'], args['b']
...@@ -815,16 +815,15 @@ Essentially, assignment always binds a name to a value; The same is true of ...@@ -815,16 +815,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 ``def`` and ``class`` statements, but in that case the value is a
callable. Consider the following code:: callable. Consider the following code::
class A: >>> class A:
pass ... pass
...
B = A >>> B = A
>>> a = B()
a = B() >>> b = a
b = a >>> print b
print b
<__main__.A instance at 0x16D07CC> <__main__.A instance at 0x16D07CC>
print a >>> print a
<__main__.A instance at 0x16D07CC> <__main__.A instance at 0x16D07CC>
Arguably the class has a name: even though it is bound to two names and invoked Arguably the class has a name: even though it is bound to two names and invoked
...@@ -1209,7 +1208,7 @@ How do I iterate over a sequence in reverse order? ...@@ -1209,7 +1208,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:: Use the :func:`reversed` built-in function, which is new in Python 2.4::
for x in reversed(sequence): 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 This won't touch your original sequence, but build a new copy with reversed
order to iterate over. order to iterate over.
...@@ -1217,7 +1216,7 @@ order to iterate over. ...@@ -1217,7 +1216,7 @@ order to iterate over.
With Python 2.3, you can use an extended slice syntax:: With Python 2.3, you can use an extended slice syntax::
for x in sequence[::-1]: for x in sequence[::-1]:
... # do something with x... ... # do something with x ...
How do you remove duplicates from a list? How do you remove duplicates from a list?
...@@ -1552,7 +1551,7 @@ A method is a function on some object ``x`` that you normally call as ...@@ -1552,7 +1551,7 @@ A method is a function on some object ``x`` that you normally call as
definition:: definition::
class C: class C:
def meth (self, arg): def meth(self, arg):
return arg * 2 + self.attribute return arg * 2 + self.attribute
...@@ -1585,9 +1584,9 @@ that does something:: ...@@ -1585,9 +1584,9 @@ that does something::
def search(obj): def search(obj):
if isinstance(obj, Mailbox): if isinstance(obj, Mailbox):
# ... code to search a mailbox ... # code to search a mailbox
elif isinstance(obj, Document): elif isinstance(obj, Document):
# ... code to search a document ... # code to search a document
elif ... elif ...
A better approach is to define a ``search()`` method on all the classes and just A better approach is to define a ``search()`` method on all the classes and just
...@@ -1595,11 +1594,11 @@ call it:: ...@@ -1595,11 +1594,11 @@ call it::
class Mailbox: class Mailbox:
def search(self): def search(self):
# ... code to search a mailbox ... # code to search a mailbox
class Document: class Document:
def search(self): def search(self):
# ... code to search a document ... # code to search a document
obj.search() obj.search()
...@@ -1656,7 +1655,7 @@ How do I call a method defined in a base class from a derived class that overrid ...@@ -1656,7 +1655,7 @@ How do I call a method defined in a base class from a derived class that overrid
If you're using new-style classes, use the built-in :func:`super` function:: If you're using new-style classes, use the built-in :func:`super` function::
class Derived(Base): class Derived(Base):
def meth (self): def meth(self):
super(Derived, self).meth() super(Derived, self).meth()
If you're using classic classes: For a class definition such as ``class If you're using classic classes: For a class definition such as ``class
......
...@@ -169,9 +169,9 @@ descriptor is useful for monitoring just a few chosen attributes:: ...@@ -169,9 +169,9 @@ descriptor is useful for monitoring just a few chosen attributes::
self.val = val self.val = val
>>> class MyClass(object): >>> class MyClass(object):
x = RevealAccess(10, 'var "x"') ... x = RevealAccess(10, 'var "x"')
y = 5 ... y = 5
...
>>> m = MyClass() >>> m = MyClass()
>>> m.x >>> m.x
Retrieving var "x" Retrieving var "x"
...@@ -293,9 +293,9 @@ this:: ...@@ -293,9 +293,9 @@ this::
Running the interpreter shows how the function descriptor works in practice:: Running the interpreter shows how the function descriptor works in practice::
>>> class D(object): >>> class D(object):
def f(self, x): ... def f(self, x):
return x ... return x
...
>>> d = D() >>> d = D()
>>> D.__dict__['f'] # Stored internally as a function >>> D.__dict__['f'] # Stored internally as a function
<function f at 0x00C45070> <function f at 0x00C45070>
...@@ -364,10 +364,10 @@ Since staticmethods return the underlying function with no changes, the example ...@@ -364,10 +364,10 @@ Since staticmethods return the underlying function with no changes, the example
calls are unexciting:: calls are unexciting::
>>> class E(object): >>> class E(object):
def f(x): ... def f(x):
print x ... print x
f = staticmethod(f) ... f = staticmethod(f)
...
>>> print E.f(3) >>> print E.f(3)
3 3
>>> print E().f(3) >>> print E().f(3)
...@@ -390,10 +390,10 @@ argument list before calling the function. This format is the same ...@@ -390,10 +390,10 @@ argument list before calling the function. This format is the same
for whether the caller is an object or a class:: for whether the caller is an object or a class::
>>> class E(object): >>> class E(object):
def f(klass, x): ... def f(klass, x):
return klass.__name__, x ... return klass.__name__, x
f = classmethod(f) ... f = classmethod(f)
...
>>> print E.f(3) >>> print E.f(3)
('E', 3) ('E', 3)
>>> print E().f(3) >>> print E().f(3)
......
...@@ -63,6 +63,7 @@ Here is the auxiliary module:: ...@@ -63,6 +63,7 @@ Here is the auxiliary module::
def __init__(self): def __init__(self):
self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary') self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
self.logger.info('creating an instance of Auxiliary') self.logger.info('creating an instance of Auxiliary')
def do_something(self): def do_something(self):
self.logger.info('doing something') self.logger.info('doing something')
a = 1 + 1 a = 1 + 1
......
...@@ -1127,19 +1127,19 @@ which can be either a string or a function, and the string to be processed. ...@@ -1127,19 +1127,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 Here's a simple example of using the :meth:`sub` method. It replaces colour
names with the word ``colour``:: names with the word ``colour``::
>>> p = re.compile( '(blue|white|red)') >>> p = re.compile('(blue|white|red)')
>>> p.sub( 'colour', 'blue socks and red shoes') >>> p.sub('colour', 'blue socks and red shoes')
'colour socks and colour 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' 'colour socks and red shoes'
The :meth:`subn` method does the same work, but returns a 2-tuple containing the 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:: new string value and the number of replacements that were performed::
>>> p = re.compile( '(blue|white|red)') >>> p = re.compile('(blue|white|red)')
>>> p.subn( 'colour', 'blue socks and red shoes') >>> p.subn('colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2) ('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) ('no colours at all', 0)
Empty matches are replaced only when they're not adjacent to a previous match. Empty matches are replaced only when they're not adjacent to a previous match.
......
...@@ -165,10 +165,10 @@ Explorer [#]_. :: ...@@ -165,10 +165,10 @@ Explorer [#]_. ::
url = 'http://www.someserver.com/cgi-bin/register.cgi' url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = {'name' : 'Michael Foord', values = {'name': 'Michael Foord',
'location' : 'Northampton', 'location': 'Northampton',
'language' : 'Python' } 'language': 'Python' }
headers = { 'User-Agent' : user_agent } headers = {'User-Agent': user_agent}
data = urllib.urlencode(values) data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers) req = urllib2.Request(url, data, headers)
......
...@@ -269,6 +269,6 @@ sample and subtract the whole output sample from the input sample:: ...@@ -269,6 +269,6 @@ sample and subtract the whole output sample from the input sample::
# out_test) # out_test)
prefill = '\0'*(pos+ipos)*2 prefill = '\0'*(pos+ipos)*2
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata)) 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) return audioop.add(inputdata, outputdata, 2)
...@@ -838,7 +838,7 @@ Since an ordered dictionary remembers its insertion order, it can be used ...@@ -838,7 +838,7 @@ Since an ordered dictionary remembers its insertion order, it can be used
in conjuction with sorting to make a sorted dictionary:: in conjuction with sorting to make a sorted dictionary::
>>> # regular unsorted 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 >>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
...@@ -1002,10 +1002,13 @@ The ABC supplies the remaining methods such as :meth:`__and__` and ...@@ -1002,10 +1002,13 @@ The ABC supplies the remaining methods such as :meth:`__and__` and
for value in iterable: for value in iterable:
if value not in lst: if value not in lst:
lst.append(value) lst.append(value)
def __iter__(self): def __iter__(self):
return iter(self.elements) return iter(self.elements)
def __contains__(self, value): def __contains__(self, value):
return value in self.elements return value in self.elements
def __len__(self): def __len__(self):
return len(self.elements) return len(self.elements)
......
...@@ -66,8 +66,10 @@ as they are encountered:: ...@@ -66,8 +66,10 @@ as they are encountered::
class MyHTMLParser(HTMLParser): class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs): def handle_starttag(self, tag, attrs):
print "Encountered a start tag:", tag print "Encountered a start tag:", tag
def handle_endtag(self, tag): def handle_endtag(self, tag):
print "Encountered an end tag :", tag print "Encountered an end tag :", tag
def handle_data(self, data): def handle_data(self, data):
print "Encountered some data :", data print "Encountered some data :", data
...@@ -252,21 +254,27 @@ examples:: ...@@ -252,21 +254,27 @@ examples::
print "Start tag:", tag print "Start tag:", tag
for attr in attrs: for attr in attrs:
print " attr:", attr print " attr:", attr
def handle_endtag(self, tag): def handle_endtag(self, tag):
print "End tag :", tag print "End tag :", tag
def handle_data(self, data): def handle_data(self, data):
print "Data :", data print "Data :", data
def handle_comment(self, data): def handle_comment(self, data):
print "Comment :", data print "Comment :", data
def handle_entityref(self, name): def handle_entityref(self, name):
c = unichr(name2codepoint[name]) c = unichr(name2codepoint[name])
print "Named ent:", c print "Named ent:", c
def handle_charref(self, name): def handle_charref(self, name):
if name.startswith('x'): if name.startswith('x'):
c = unichr(int(name[1:], 16)) c = unichr(int(name[1:], 16))
else: else:
c = unichr(int(name)) c = unichr(int(name))
print "Num ent :", c print "Num ent :", c
def handle_decl(self, data): def handle_decl(self, data):
print "Decl :", data print "Decl :", data
...@@ -298,7 +306,7 @@ further parsing:: ...@@ -298,7 +306,7 @@ further parsing::
attr: ('type', 'text/css') attr: ('type', 'text/css')
Data : #python { color: green } Data : #python { color: green }
End tag : style End tag : style
>>>
>>> parser.feed('<script type="text/javascript">' >>> parser.feed('<script type="text/javascript">'
... 'alert("<strong>hello!</strong>");</script>') ... 'alert("<strong>hello!</strong>");</script>')
Start tag: script Start tag: script
......
...@@ -70,7 +70,7 @@ standard. However, mailcap files are supported on most Unix systems. ...@@ -70,7 +70,7 @@ standard. However, mailcap files are supported on most Unix systems.
An example usage:: An example usage::
>>> import mailcap >>> import mailcap
>>> d=mailcap.getcaps() >>> d = mailcap.getcaps()
>>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223') >>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
('xmpeg tmp1223', {'view': 'xmpeg %s'}) ('xmpeg tmp1223', {'view': 'xmpeg %s'})
...@@ -27,7 +27,7 @@ GNU/POSIX syntax, and additionally generates usage and help messages for you. ...@@ -27,7 +27,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:: Here's an example of using :mod:`optparse` in a simple script::
from optparse import OptionParser from optparse import OptionParser
[...] ...
parser = OptionParser() parser = OptionParser()
parser.add_option("-f", "--file", dest="filename", parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE") help="write report to FILE", metavar="FILE")
...@@ -254,7 +254,7 @@ First, you need to import the OptionParser class; then, early in the main ...@@ -254,7 +254,7 @@ First, you need to import the OptionParser class; then, early in the main
program, create an OptionParser instance:: program, create an OptionParser instance::
from optparse import OptionParser from optparse import OptionParser
[...] ...
parser = OptionParser() parser = OptionParser()
Then you can start defining options. The basic syntax is:: Then you can start defining options. The basic syntax is::
...@@ -721,7 +721,7 @@ you can call :func:`OptionParser.error` to signal an application-defined error ...@@ -721,7 +721,7 @@ you can call :func:`OptionParser.error` to signal an application-defined error
condition:: condition::
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
[...] ...
if options.a and options.b: if options.a and options.b:
parser.error("options -a and -b are mutually exclusive") parser.error("options -a and -b are mutually exclusive")
...@@ -761,7 +761,7 @@ Putting it all together ...@@ -761,7 +761,7 @@ Putting it all together
Here's what :mod:`optparse`\ -based scripts usually look like:: Here's what :mod:`optparse`\ -based scripts usually look like::
from optparse import OptionParser from optparse import OptionParser
[...] ...
def main(): def main():
usage = "usage: %prog [options] arg" usage = "usage: %prog [options] arg"
parser = OptionParser(usage) parser = OptionParser(usage)
...@@ -771,13 +771,13 @@ Here's what :mod:`optparse`\ -based scripts usually look like:: ...@@ -771,13 +771,13 @@ Here's what :mod:`optparse`\ -based scripts usually look like::
action="store_true", dest="verbose") action="store_true", dest="verbose")
parser.add_option("-q", "--quiet", parser.add_option("-q", "--quiet",
action="store_false", dest="verbose") action="store_false", dest="verbose")
[...] ...
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if len(args) != 1: if len(args) != 1:
parser.error("incorrect number of arguments") parser.error("incorrect number of arguments")
if options.verbose: if options.verbose:
print "reading %s..." % options.filename print "reading %s..." % options.filename
[...] ...
if __name__ == "__main__": if __name__ == "__main__":
main() main()
...@@ -1412,7 +1412,7 @@ If you're not careful, it's easy to define options with conflicting option ...@@ -1412,7 +1412,7 @@ If you're not careful, it's easy to define options with conflicting option
strings:: strings::
parser.add_option("-n", "--dry-run", ...) parser.add_option("-n", "--dry-run", ...)
[...] ...
parser.add_option("-n", "--noisy", ...) parser.add_option("-n", "--noisy", ...)
(This is particularly true if you've defined your own OptionParser subclass with (This is particularly true if you've defined your own OptionParser subclass with
...@@ -1453,7 +1453,7 @@ that option. If the user asks for help, the help message will reflect that:: ...@@ -1453,7 +1453,7 @@ that option. If the user asks for help, the help message will reflect that::
Options: Options:
--dry-run do no harm --dry-run do no harm
[...] ...
-n, --noisy be noisy -n, --noisy be noisy
It's possible to whittle away the option strings for a previously-added option It's possible to whittle away the option strings for a previously-added option
...@@ -1468,7 +1468,7 @@ At this point, the original ``-n``/``--dry-run`` option is no longer ...@@ -1468,7 +1468,7 @@ At this point, the original ``-n``/``--dry-run`` option is no longer
accessible, so :mod:`optparse` removes it, leaving this help text:: accessible, so :mod:`optparse` removes it, leaving this help text::
Options: Options:
[...] ...
-n, --noisy be noisy -n, --noisy be noisy
--dry-run new dry-run option --dry-run new dry-run option
...@@ -1704,7 +1704,7 @@ seen, but blow up if it comes after ``-b`` in the command-line. :: ...@@ -1704,7 +1704,7 @@ seen, but blow up if it comes after ``-b`` in the command-line. ::
if parser.values.b: if parser.values.b:
raise OptionValueError("can't use -a after -b") raise OptionValueError("can't use -a after -b")
parser.values.a = 1 parser.values.a = 1
[...] ...
parser.add_option("-a", action="callback", callback=check_order) parser.add_option("-a", action="callback", callback=check_order)
parser.add_option("-b", action="store_true", dest="b") parser.add_option("-b", action="store_true", dest="b")
...@@ -1722,7 +1722,7 @@ message and the flag that it sets must be generalized. :: ...@@ -1722,7 +1722,7 @@ message and the flag that it sets must be generalized. ::
if parser.values.b: if parser.values.b:
raise OptionValueError("can't use %s after -b" % opt_str) raise OptionValueError("can't use %s after -b" % opt_str)
setattr(parser.values, option.dest, 1) setattr(parser.values, option.dest, 1)
[...] ...
parser.add_option("-a", action="callback", callback=check_order, dest='a') parser.add_option("-a", action="callback", callback=check_order, dest='a')
parser.add_option("-b", action="store_true", dest="b") parser.add_option("-b", action="store_true", dest="b")
parser.add_option("-c", action="callback", callback=check_order, dest='c') parser.add_option("-c", action="callback", callback=check_order, dest='c')
...@@ -1742,7 +1742,7 @@ should not be called when the moon is full, all you have to do is this:: ...@@ -1742,7 +1742,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" raise OptionValueError("%s option invalid when moon is full"
% opt_str) % opt_str)
setattr(parser.values, option.dest, 1) setattr(parser.values, option.dest, 1)
[...] ...
parser.add_option("--foo", parser.add_option("--foo",
action="callback", callback=check_moon, dest="foo") action="callback", callback=check_moon, dest="foo")
...@@ -1765,7 +1765,7 @@ Here's an example that just emulates the standard ``"store"`` action:: ...@@ -1765,7 +1765,7 @@ Here's an example that just emulates the standard ``"store"`` action::
def store_value(option, opt_str, value, parser): def store_value(option, opt_str, value, parser):
setattr(parser.values, option.dest, value) setattr(parser.values, option.dest, value)
[...] ...
parser.add_option("--foo", parser.add_option("--foo",
action="callback", callback=store_value, action="callback", callback=store_value,
type="int", nargs=3, dest="foo") type="int", nargs=3, dest="foo")
...@@ -1827,7 +1827,7 @@ arguments:: ...@@ -1827,7 +1827,7 @@ arguments::
del parser.rargs[:len(value)] del parser.rargs[:len(value)]
setattr(parser.values, option.dest, value) setattr(parser.values, option.dest, value)
[...] ...
parser.add_option("-c", "--callback", dest="vararg_attr", parser.add_option("-c", "--callback", dest="vararg_attr",
action="callback", callback=vararg_callback) action="callback", callback=vararg_callback)
......
...@@ -887,6 +887,7 @@ Example of changing the attribute "target" of every link in first paragraph:: ...@@ -887,6 +887,7 @@ Example of changing the attribute "target" of every link in first paragraph::
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>] [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links: # Iterates through all found links >>> for i in links: # Iterates through all found links
... i.attrib["target"] = "blank" ... i.attrib["target"] = "blank"
...
>>> tree.write("output.xhtml") >>> tree.write("output.xhtml")
.. _elementtree-qname-objects: .. _elementtree-qname-objects:
......
...@@ -235,7 +235,7 @@ A working example follows. The server code:: ...@@ -235,7 +235,7 @@ A working example follows. The server code::
from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCServer
def is_even(n): def is_even(n):
return n%2 == 0 return n % 2 == 0
server = SimpleXMLRPCServer(("localhost", 8000)) server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..." print "Listening on port 8000..."
...@@ -392,7 +392,7 @@ returning a complex type object. The server code:: ...@@ -392,7 +392,7 @@ returning a complex type object. The server code::
# A marshalling error is going to occur because we're returning a # A marshalling error is going to occur because we're returning a
# complex number # complex number
def add(x,y): def add(x, y):
return x+y+0j return x+y+0j
server = SimpleXMLRPCServer(("localhost", 8000)) server = SimpleXMLRPCServer(("localhost", 8000))
...@@ -590,12 +590,15 @@ transport. The following example shows how: ...@@ -590,12 +590,15 @@ transport. The following example shows how:
class ProxiedTransport(xmlrpclib.Transport): class ProxiedTransport(xmlrpclib.Transport):
def set_proxy(self, proxy): def set_proxy(self, proxy):
self.proxy = proxy self.proxy = proxy
def make_connection(self, host): def make_connection(self, host):
self.realhost = host self.realhost = host
h = httplib.HTTPConnection(self.proxy) h = httplib.HTTPConnection(self.proxy)
return h return h
def send_request(self, connection, handler, request_body): def send_request(self, connection, handler, request_body):
connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler)) connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
def send_host(self, connection, host): def send_host(self, connection, host):
connection.putheader('Host', self.realhost) connection.putheader('Host', self.realhost)
......
...@@ -210,6 +210,7 @@ definition looked like this:: ...@@ -210,6 +210,7 @@ definition looked like this::
class MyClass: class MyClass:
"""A simple example class""" """A simple example class"""
i = 12345 i = 12345
def f(self): def f(self):
return 'hello world' return 'hello world'
...@@ -458,8 +459,10 @@ variable in the class is also ok. For example:: ...@@ -458,8 +459,10 @@ variable in the class is also ok. For example::
class C: class C:
f = f1 f = f1
def g(self): def g(self):
return 'hello world' return 'hello world'
h = g h = g
Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to
...@@ -473,8 +476,10 @@ argument:: ...@@ -473,8 +476,10 @@ argument::
class Bag: class Bag:
def __init__(self): def __init__(self):
self.data = [] self.data = []
def add(self, x): def add(self, x):
self.data.append(x) self.data.append(x)
def addtwice(self, x): def addtwice(self, x):
self.add(x) self.add(x)
self.add(x) self.add(x)
...@@ -796,8 +801,10 @@ defines :meth:`~iterator.next`, then :meth:`__iter__` can just return ``self``:: ...@@ -796,8 +801,10 @@ defines :meth:`~iterator.next`, then :meth:`__iter__` can just return ``self``::
def __init__(self, data): def __init__(self, data):
self.data = data self.data = data
self.index = len(data) self.index = len(data)
def __iter__(self): def __iter__(self):
return self return self
def next(self): def next(self):
if self.index == 0: if self.index == 0:
raise StopIteration raise StopIteration
......
...@@ -236,7 +236,7 @@ If you want to concatenate variables or a variable and a literal, use ``+``:: ...@@ -236,7 +236,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:: This feature is particularly useful when you want to break long strings::
>>> text = ('Put several strings within parentheses ' >>> text = ('Put several strings within parentheses '
'to have them joined together.') ... 'to have them joined together.')
>>> text >>> text
'Put several strings within parentheses to have them joined together.' 'Put several strings within parentheses to have them joined together.'
......
...@@ -178,6 +178,7 @@ tasks in background while the main program continues to run:: ...@@ -178,6 +178,7 @@ tasks in background while the main program continues to run::
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.infile = infile self.infile = infile
self.outfile = outfile self.outfile = outfile
def run(self): def run(self):
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
f.write(self.infile) f.write(self.infile)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment