Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
12d547a8
Commit
12d547a8
authored
May 10, 2016
by
Serhiy Storchaka
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Issue #23921: Standardized documentation whitespace formatting.
Original patch by James Edwards.
parent
09f1679a
Changes
43
Hide whitespace changes
Inline
Side-by-side
Showing
43 changed files
with
269 additions
and
243 deletions
+269
-243
Doc/faq/design.rst
Doc/faq/design.rst
+10
-8
Doc/faq/library.rst
Doc/faq/library.rst
+6
-5
Doc/faq/programming.rst
Doc/faq/programming.rst
+19
-20
Doc/howto/descriptor.rst
Doc/howto/descriptor.rst
+32
-32
Doc/howto/functional.rst
Doc/howto/functional.rst
+5
-5
Doc/howto/logging-cookbook.rst
Doc/howto/logging-cookbook.rst
+16
-15
Doc/howto/logging.rst
Doc/howto/logging.rst
+2
-2
Doc/howto/regex.rst
Doc/howto/regex.rst
+6
-6
Doc/howto/urllib2.rst
Doc/howto/urllib2.rst
+4
-4
Doc/howto/webservers.rst
Doc/howto/webservers.rst
+1
-1
Doc/library/argparse.rst
Doc/library/argparse.rst
+9
-9
Doc/library/asynchat.rst
Doc/library/asynchat.rst
+1
-1
Doc/library/audioop.rst
Doc/library/audioop.rst
+1
-1
Doc/library/collections.rst
Doc/library/collections.rst
+4
-1
Doc/library/configparser.rst
Doc/library/configparser.rst
+4
-4
Doc/library/ctypes.rst
Doc/library/ctypes.rst
+32
-32
Doc/library/getopt.rst
Doc/library/getopt.rst
+1
-1
Doc/library/htmlparser.rst
Doc/library/htmlparser.rst
+9
-1
Doc/library/locale.rst
Doc/library/locale.rst
+5
-5
Doc/library/mailcap.rst
Doc/library/mailcap.rst
+1
-1
Doc/library/mmap.rst
Doc/library/mmap.rst
+1
-1
Doc/library/multiprocessing.rst
Doc/library/multiprocessing.rst
+4
-4
Doc/library/optparse.rst
Doc/library/optparse.rst
+16
-16
Doc/library/re.rst
Doc/library/re.rst
+7
-7
Doc/library/ssl.rst
Doc/library/ssl.rst
+1
-1
Doc/library/string.rst
Doc/library/string.rst
+6
-6
Doc/library/threading.rst
Doc/library/threading.rst
+1
-1
Doc/library/unittest.rst
Doc/library/unittest.rst
+13
-13
Doc/library/wsgiref.rst
Doc/library/wsgiref.rst
+4
-4
Doc/library/xml.dom.minidom.rst
Doc/library/xml.dom.minidom.rst
+2
-2
Doc/library/xml.etree.elementtree.rst
Doc/library/xml.etree.elementtree.rst
+12
-11
Doc/library/xmlrpclib.rst
Doc/library/xmlrpclib.rst
+5
-2
Doc/reference/expressions.rst
Doc/reference/expressions.rst
+1
-1
Doc/reference/simple_stmts.rst
Doc/reference/simple_stmts.rst
+2
-2
Doc/tutorial/appendix.rst
Doc/tutorial/appendix.rst
+1
-1
Doc/tutorial/classes.rst
Doc/tutorial/classes.rst
+8
-1
Doc/tutorial/controlflow.rst
Doc/tutorial/controlflow.rst
+1
-1
Doc/tutorial/errors.rst
Doc/tutorial/errors.rst
+7
-7
Doc/tutorial/inputoutput.rst
Doc/tutorial/inputoutput.rst
+2
-2
Doc/tutorial/introduction.rst
Doc/tutorial/introduction.rst
+4
-4
Doc/tutorial/modules.rst
Doc/tutorial/modules.rst
+1
-1
Doc/tutorial/stdlib.rst
Doc/tutorial/stdlib.rst
+1
-1
Doc/tutorial/stdlib2.rst
Doc/tutorial/stdlib2.rst
+1
-0
No files found.
Doc/faq/design.rst
View file @
12d547a8
...
@@ -169,7 +169,7 @@ where in Python you're forced to write this::
...
@@ -169,7 +169,7 @@ where in Python you're forced to write this::
line = f.readline()
line = f.readline()
if not line:
if not line:
break
break
... # do something with line
...
# do something with line
The reason for not allowing assignment in Python expressions is a common,
The reason for not allowing assignment in Python expressions is a common,
hard-to-find bug in those other languages, caused by this construct:
hard-to-find bug in those other languages, caused by this construct:
...
@@ -201,7 +201,7 @@ generally less robust than the "while True" solution::
...
@@ -201,7 +201,7 @@ generally less robust than the "while True" solution::
line = f.readline()
line = f.readline()
while line:
while line:
... # do something with line...
...
# do something with line...
line = f.readline()
line = f.readline()
The problem with this is that if you change your mind about exactly how you get
The problem with this is that if you change your mind about exactly how you get
...
@@ -214,7 +214,7 @@ objects using the ``for`` statement. For example, in the current version of
...
@@ -214,7 +214,7 @@ objects using the ``for`` statement. For example, in the current version of
Python file objects support the iterator protocol, so you can now write simply::
Python file objects support the iterator protocol, so you can now write simply::
for line in f:
for line in f:
... # do something with line...
...
# do something with line...
...
@@ -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
...
@@ -667,7 +669,7 @@ it. For example, here's how to iterate over the keys of a dictionary in sorted
...
@@ -667,7 +669,7 @@ it. For example, here's how to iterate over the keys of a dictionary in sorted
order::
order::
for key in sorted(mydict):
for key in sorted(mydict):
... # do whatever with mydict[key]...
...
# do whatever with mydict[key]...
How do you specify and enforce an interface spec in Python?
How do you specify and enforce an interface spec in Python?
...
@@ -723,11 +725,11 @@ languages. For example::
...
@@ -723,11 +725,11 @@ languages. For example::
class label: pass # declare a label
class label: pass # declare a label
try:
try:
...
...
if condition: raise label() # goto label
if condition: raise label() # goto label
...
...
except label: # where to goto
except label: # where to goto
pass
pass
...
...
This doesn't allow you to jump into the middle of a loop, but that's usually
This doesn't allow you to jump into the middle of a loop, but that's usually
...
...
Doc/faq/library.rst
View file @
12d547a8
...
@@ -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")
...
...
Doc/faq/programming.rst
View file @
12d547a8
...
@@ -353,7 +353,7 @@ functions), e.g.::
...
@@ -353,7 +353,7 @@ functions), e.g.::
>>> squares = []
>>> squares = []
>>> for x in range(5):
>>> for x in range(5):
... squares.append(lambda: x**2)
...
squares.append(lambda: x**2)
This gives you a list that contains 5 lambdas that calculate ``x**2``. You
This gives you a list that contains 5 lambdas that calculate ``x**2``. You
might expect that, when called, they would return, respectively, ``0``, ``1``,
might expect that, when called, they would return, respectively, ``0``, ``1``,
...
@@ -380,7 +380,7 @@ lambdas, so that they don't rely on the value of the global ``x``::
...
@@ -380,7 +380,7 @@ lambdas, so that they don't rely on the value of the global ``x``::
>>> squares = []
>>> squares = []
>>> for x in range(5):
>>> for x in range(5):
... squares.append(lambda n=x: n**2)
...
squares.append(lambda n=x: n**2)
Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
when the lambda is defined so that it has the same value that ``x`` had at
when the lambda is defined so that it has the same value that ``x`` had at
...
@@ -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
...
...
Doc/howto/descriptor.rst
View file @
12d547a8
...
@@ -108,7 +108,7 @@ like::
...
@@ -108,7 +108,7 @@ like::
"Emulate type_getattro() in Objects/typeobject.c"
"Emulate type_getattro() in Objects/typeobject.c"
v = object.__getattribute__(self, key)
v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v.__get__(None, self)
return v
return v
The important points to remember are:
The important points to remember are:
...
@@ -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,15 +293,15 @@ this::
...
@@ -293,15 +293,15 @@ 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>
>>> D.f # Get from a class becomes an unbound method
>>> D.f
# Get from a class becomes an unbound method
<unbound method D.f>
<unbound method D.f>
>>> d.f # Get from an instance becomes a bound method
>>> d.f
# Get from an instance becomes a bound method
<bound method D.f of <__main__.D object at 0x00B18C90>>
<bound method D.f of <__main__.D object at 0x00B18C90>>
The output suggests that bound and unbound methods are two different types.
The output suggests that bound and unbound methods are two different types.
...
@@ -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)
...
@@ -377,23 +377,23 @@ Using the non-data descriptor protocol, a pure Python version of
...
@@ -377,23 +377,23 @@ Using the non-data descriptor protocol, a pure Python version of
:func:`staticmethod` would look like this::
:func:`staticmethod` would look like this::
class StaticMethod(object):
class StaticMethod(object):
"Emulate PyStaticMethod_Type() in Objects/funcobject.c"
"Emulate PyStaticMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
def __init__(self, f):
self.f = f
self.f = f
def __get__(self, obj, objtype=None):
def __get__(self, obj, objtype=None):
return self.f
return self.f
Unlike static methods, class methods prepend the class reference to the
Unlike static methods, class methods prepend the class reference to the
argument list before calling the function. This format is the same
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)
...
@@ -425,15 +425,15 @@ Using the non-data descriptor protocol, a pure Python version of
...
@@ -425,15 +425,15 @@ Using the non-data descriptor protocol, a pure Python version of
:func:`classmethod` would look like this::
:func:`classmethod` would look like this::
class ClassMethod(object):
class ClassMethod(object):
"Emulate PyClassMethod_Type() in Objects/funcobject.c"
"Emulate PyClassMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
def __init__(self, f):
self.f = f
self.f = f
def __get__(self, obj, klass=None):
def __get__(self, obj, klass=None):
if klass is None:
if klass is None:
klass = type(obj)
klass = type(obj)
def newfunc(*args):
def newfunc(*args):
return self.f(klass, *args)
return self.f(klass, *args)
return newfunc
return newfunc
Doc/howto/functional.rst
View file @
12d547a8
...
@@ -394,14 +394,14 @@ equivalent to the following Python code::
...
@@ -394,14 +394,14 @@ equivalent to the following Python code::
continue # Skip this element
continue # Skip this element
for expr2 in sequence2:
for expr2 in sequence2:
if not (condition2):
if not (condition2):
continue
# Skip this element
continue # Skip this element
...
...
for exprN in sequenceN:
for exprN in sequenceN:
if not (conditionN):
if not (conditionN):
continue # Skip this element
continue # Skip this element
# Output the value of
# Output the value of
# the expression.
# the expression.
This means that when there are multiple ``for...in`` clauses but no ``if``
This means that when there are multiple ``for...in`` clauses but no ``if``
clauses, the length of the resulting output will be equal to the product of the
clauses, the length of the resulting output will be equal to the product of the
...
...
Doc/howto/logging-cookbook.rst
View file @
12d547a8
...
@@ -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
...
@@ -585,21 +586,21 @@ script::
...
@@ -585,21 +586,21 @@ script::
return True
return True
if __name__ == '__main__':
if __name__ == '__main__':
levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
logging.basicConfig(level=logging.DEBUG,
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
a1 = logging.getLogger('a.b.c')
a1 = logging.getLogger('a.b.c')
a2 = logging.getLogger('d.e.f')
a2 = logging.getLogger('d.e.f')
f = ContextFilter()
f = ContextFilter()
a1.addFilter(f)
a1.addFilter(f)
a2.addFilter(f)
a2.addFilter(f)
a1.debug('A debug message')
a1.debug('A debug message')
a1.info('An info message with %s', 'some parameters')
a1.info('An info message with %s', 'some parameters')
for x in range(10):
for x in range(10):
lvl = choice(levels)
lvl = choice(levels)
lvlname = logging.getLevelName(lvl)
lvlname = logging.getLevelName(lvl)
a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
which, when run, produces something like::
which, when run, produces something like::
...
...
Doc/howto/logging.rst
View file @
12d547a8
...
@@ -103,8 +103,8 @@ A simple example
...
@@ -103,8 +103,8 @@ A simple example
A very simple example is::
A very simple example is::
import logging
import logging
logging.warning('Watch out!') # will print a message to the console
logging.warning('Watch out!')
# will print a message to the console
logging.info('I told you so') # will not print anything
logging.info('I told you so')
# will not print anything
If you type these lines into a script and run it, you'll see::
If you type these lines into a script and run it, you'll see::
...
...
Doc/howto/regex.rst
View file @
12d547a8
...
@@ -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.
...
...
Doc/howto/urllib2.rst
View file @
12d547a8
...
@@ -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)
...
...
Doc/howto/webservers.rst
View file @
12d547a8
...
@@ -295,7 +295,7 @@ following WSGI-application::
...
@@ -295,7 +295,7 @@ following WSGI-application::
yield '
<h1>
FastCGI Environment
</h1>
'
yield '
<h1>
FastCGI Environment
</h1>
'
yield '
<table>
'
yield '
<table>
'
for k, v in sorted(environ.items()):
for k, v in sorted(environ.items()):
yield '
<tr><th>
%s
</th><td>
%s
</td></tr>
' % (escape(k), escape(v))
yield '
<tr><th>
%s
</th><td>
%s
</td></tr>
' % (escape(k), escape(v))
yield '
</table>
'
yield '
</table>
'
WSGIServer(app).run()
WSGIServer(app).run()
...
...
Doc/library/argparse.rst
View file @
12d547a8
...
@@ -35,10 +35,10 @@ produces either the sum or the max::
...
@@ -35,10 +35,10 @@ produces either the sum or the max::
parser = argparse.ArgumentParser(description='Process some integers.')
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
const=sum, default=max,
help='sum the integers (default: find the max)')
help='sum the integers (default: find the max)')
args = parser.parse_args()
args = parser.parse_args()
print args.accumulate(args.integers)
print args.accumulate(args.integers)
...
@@ -463,7 +463,7 @@ specified characters will be treated as files, and will be replaced by the
...
@@ -463,7 +463,7 @@ specified characters will be treated as files, and will be replaced by the
arguments they contain. For example::
arguments they contain. For example::
>>> with open('args.txt', 'w') as fp:
>>> with open('args.txt', 'w') as fp:
... fp.write('-f\nbar')
...
fp.write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
...
@@ -1064,9 +1064,9 @@ argument::
...
@@ -1064,9 +1064,9 @@ argument::
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', action='store_true',
>>> parser.add_argument('--foo', action='store_true',
... help='foo the bars before frobbling')
...
help='foo the bars before frobbling')
>>> parser.add_argument('bar', nargs='+',
>>> parser.add_argument('bar', nargs='+',
... help='one of the bars to be frobbled')
...
help='one of the bars to be frobbled')
>>> parser.parse_args(['-h'])
>>> parser.parse_args(['-h'])
usage: frobble [-h] [--foo] bar [bar ...]
usage: frobble [-h] [--foo] bar [bar ...]
...
@@ -1084,7 +1084,7 @@ specifiers include the program name, ``%(prog)s`` and most keyword arguments to
...
@@ -1084,7 +1084,7 @@ specifiers include the program name, ``%(prog)s`` and most keyword arguments to
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
... help='the bar to %(prog)s (default: %(default)s)')
...
help='the bar to %(prog)s (default: %(default)s)')
>>> parser.print_help()
>>> parser.print_help()
usage: frobble [-h] [bar]
usage: frobble [-h] [bar]
...
@@ -1417,10 +1417,10 @@ interactive prompt::
...
@@ -1417,10 +1417,10 @@ interactive prompt::
>>> parser = argparse.ArgumentParser()
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
>>> parser.add_argument(
... 'integers', metavar='int', type=int, choices=xrange(10),
... 'integers', metavar='int', type=int, choices=xrange(10),
... nargs='+', help='an integer in the range 0..9')
...
nargs='+', help='an integer in the range 0..9')
>>> parser.add_argument(
>>> parser.add_argument(
... '--sum', dest='accumulate', action='store_const', const=sum,
... '--sum', dest='accumulate', action='store_const', const=sum,
... default=max, help='sum the integers (default: find the max)')
...
default=max, help='sum the integers (default: find the max)')
>>> parser.parse_args(['1', '2', '3', '4'])
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
...
...
Doc/library/asynchat.rst
View file @
12d547a8
...
@@ -228,7 +228,7 @@ any extraneous data sent by the web client are ignored. ::
...
@@ -228,7 +228,7 @@ any extraneous data sent by the web client are ignored. ::
self.set_terminator(None)
self.set_terminator(None)
self.handle_request()
self.handle_request()
elif not self.handling:
elif not self.handling:
self.set_terminator(None) # browsers sometimes over-send
self.set_terminator(None)
# browsers sometimes over-send
self.cgi_data = parse(self.headers, "".join(self.ibuffer))
self.cgi_data = parse(self.headers, "".join(self.ibuffer))
self.handling = True
self.handling = True
self.ibuffer = []
self.ibuffer = []
...
...
Doc/library/audioop.rst
View file @
12d547a8
...
@@ -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)
Doc/library/collections.rst
View file @
12d547a8
...
@@ -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)
...
...
Doc/library/configparser.rst
View file @
12d547a8
...
@@ -489,8 +489,8 @@ To get interpolation, you will need to use a :class:`ConfigParser` or
...
@@ -489,8 +489,8 @@ To get interpolation, you will need to use a :class:`ConfigParser` or
config.read('example.cfg')
config.read('example.cfg')
# Set the third, optional argument of get to 1 if you wish to use raw mode.
# Set the third, optional argument of get to 1 if you wish to use raw mode.
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 0)
# -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
print config.get('Section1', 'foo', 1)
# -> "%(bar)s is %(baz)s!"
# The optional fourth argument is a dict with members that will take
# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
# precedence in interpolation.
...
@@ -506,10 +506,10 @@ interpolation if an option used is not defined elsewhere. ::
...
@@ -506,10 +506,10 @@ interpolation if an option used is not defined elsewhere. ::
config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')
config.read('example.cfg')
print config.get('Section1', 'foo') # -> "Python is fun!"
print config.get('Section1', 'foo')
# -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
config.remove_option('Section1', 'baz')
print config.get('Section1', 'foo') # -> "Life is hard!"
print config.get('Section1', 'foo')
# -> "Life is hard!"
The function ``opt_move`` below can be used to move options between sections::
The function ``opt_move`` below can be used to move options between sections::
...
...
Doc/library/ctypes.rst
View file @
12d547a8
...
@@ -49,11 +49,11 @@ library containing most standard C functions, and uses the cdecl calling
...
@@ -49,11 +49,11 @@ library containing most standard C functions, and uses the cdecl calling
convention::
convention::
>>> from ctypes import *
>>> from ctypes import *
>>> print windll.kernel32 # doctest: +WINDOWS
>>> print windll.kernel32
# doctest: +WINDOWS
<WinDLL 'kernel32', handle ... at ...>
<WinDLL 'kernel32', handle ... at ...>
>>> print cdll.msvcrt # doctest: +WINDOWS
>>> print cdll.msvcrt
# doctest: +WINDOWS
<CDLL 'msvcrt', handle ... at ...>
<CDLL 'msvcrt', handle ... at ...>
>>> libc = cdll.msvcrt # doctest: +WINDOWS
>>> libc = cdll.msvcrt
# doctest: +WINDOWS
>>>
>>>
Windows appends the usual ``.dll`` file suffix automatically.
Windows appends the usual ``.dll`` file suffix automatically.
...
@@ -63,10 +63,10 @@ load a library, so attribute access can not be used to load libraries. Either th
...
@@ -63,10 +63,10 @@ load a library, so attribute access can not be used to load libraries. Either th
:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
the library by creating an instance of CDLL by calling the constructor::
the library by creating an instance of CDLL by calling the constructor::
>>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
>>> cdll.LoadLibrary("libc.so.6")
# doctest: +LINUX
<CDLL 'libc.so.6', handle ... at ...>
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6") # doctest: +LINUX
>>> libc = CDLL("libc.so.6")
# doctest: +LINUX
>>> libc # doctest: +LINUX
>>> libc
# doctest: +LINUX
<CDLL 'libc.so.6', handle ... at ...>
<CDLL 'libc.so.6', handle ... at ...>
>>>
>>>
...
@@ -83,9 +83,9 @@ Functions are accessed as attributes of dll objects::
...
@@ -83,9 +83,9 @@ Functions are accessed as attributes of dll objects::
>>> from ctypes import *
>>> from ctypes import *
>>> libc.printf
>>> libc.printf
<_FuncPtr object at 0x...>
<_FuncPtr object at 0x...>
>>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
>>> print windll.kernel32.GetModuleHandleA
# doctest: +WINDOWS
<_FuncPtr object at 0x...>
<_FuncPtr object at 0x...>
>>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
>>> print windll.kernel32.MyOwnFunction
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
File "ctypes.py", line 239, in __getattr__
File "ctypes.py", line 239, in __getattr__
...
@@ -115,16 +115,16 @@ Sometimes, dlls export functions with names which aren't valid Python
...
@@ -115,16 +115,16 @@ Sometimes, dlls export functions with names which aren't valid Python
identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
:func:`getattr` to retrieve the function::
:func:`getattr` to retrieve the function::
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")
# doctest: +WINDOWS
<_FuncPtr object at 0x...>
<_FuncPtr object at 0x...>
>>>
>>>
On Windows, some dlls export functions not by name but by ordinal. These
On Windows, some dlls export functions not by name but by ordinal. These
functions can be accessed by indexing the dll object with the ordinal number::
functions can be accessed by indexing the dll object with the ordinal number::
>>> cdll.kernel32[1] # doctest: +WINDOWS
>>> cdll.kernel32[1]
# doctest: +WINDOWS
<_FuncPtr object at 0x...>
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0] # doctest: +WINDOWS
>>> cdll.kernel32[0]
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
File "ctypes.py", line 310, in __getitem__
File "ctypes.py", line 310, in __getitem__
...
@@ -146,9 +146,9 @@ handle.
...
@@ -146,9 +146,9 @@ handle.
This example calls both functions with a NULL pointer (``None`` should be used
This example calls both functions with a NULL pointer (``None`` should be used
as the NULL pointer)::
as the NULL pointer)::
>>> print libc.time(None) # doctest: +SKIP
>>> print libc.time(None)
# doctest: +SKIP
1150640792
1150640792
>>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
>>> print hex(windll.kernel32.GetModuleHandleA(None))
# doctest: +WINDOWS
0x1d000000
0x1d000000
>>>
>>>
...
@@ -157,11 +157,11 @@ of arguments or the wrong calling convention. Unfortunately this only works on
...
@@ -157,11 +157,11 @@ of arguments or the wrong calling convention. Unfortunately this only works on
Windows. It does this by examining the stack after the function returns, so
Windows. It does this by examining the stack after the function returns, so
although an error is raised the function *has* been called::
although an error is raised the function *has* been called::
>>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
>>> windll.kernel32.GetModuleHandleA()
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
>>> windll.kernel32.GetModuleHandleA(0, 0)
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
...
@@ -170,13 +170,13 @@ although an error is raised the function *has* been called::
...
@@ -170,13 +170,13 @@ although an error is raised the function *has* been called::
The same exception is raised when you call an ``stdcall`` function with the
The same exception is raised when you call an ``stdcall`` function with the
``cdecl`` calling convention, or vice versa::
``cdecl`` calling convention, or vice versa::
>>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
>>> cdll.kernel32.GetModuleHandleA(None)
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>
>>>
>>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
>>> windll.msvcrt.printf("spam")
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
...
@@ -189,7 +189,7 @@ On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
...
@@ -189,7 +189,7 @@ On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
crashes from general protection faults when functions are called with invalid
crashes from general protection faults when functions are called with invalid
argument values::
argument values::
>>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
>>> windll.kernel32.GetModuleHandleA(32)
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
WindowsError: exception: access violation reading 0x00000020
WindowsError: exception: access violation reading 0x00000020
...
@@ -448,9 +448,9 @@ Here is a more advanced example, it uses the ``strchr`` function, which expects
...
@@ -448,9 +448,9 @@ Here is a more advanced example, it uses the ``strchr`` function, which expects
a string pointer and a char, and returns a pointer to a string::
a string pointer and a char, and returns a pointer to a string::
>>> strchr = libc.strchr
>>> strchr = libc.strchr
>>> strchr("abcdef", ord("d")) # doctest: +SKIP
>>> strchr("abcdef", ord("d"))
# doctest: +SKIP
8059983
8059983
>>> strchr.restype = c_char_p # c_char_p is a pointer to a string
>>> strchr.restype = c_char_p
# c_char_p is a pointer to a string
>>> strchr("abcdef", ord("d"))
>>> strchr("abcdef", ord("d"))
'def'
'def'
>>> print strchr("abcdef", ord("x"))
>>> print strchr("abcdef", ord("x"))
...
@@ -481,17 +481,17 @@ callable will be called with the *integer* the C function returns, and the
...
@@ -481,17 +481,17 @@ callable will be called with the *integer* the C function returns, and the
result of this call will be used as the result of your function call. This is
result of this call will be used as the result of your function call. This is
useful to check for error return values and automatically raise an exception::
useful to check for error return values and automatically raise an exception::
>>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
>>> GetModuleHandle = windll.kernel32.GetModuleHandleA
# doctest: +WINDOWS
>>> def ValidHandle(value):
>>> def ValidHandle(value):
... if value == 0:
... if value == 0:
... raise WinError()
... raise WinError()
... return value
... return value
...
...
>>>
>>>
>>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
>>> GetModuleHandle.restype = ValidHandle
# doctest: +WINDOWS
>>> GetModuleHandle(None) # doctest: +WINDOWS
>>> GetModuleHandle(None)
# doctest: +WINDOWS
486539264
486539264
>>> GetModuleHandle("something silly") # doctest: +WINDOWS
>>> GetModuleHandle("something silly")
# doctest: +WINDOWS
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in ValidHandle
File "<stdin>", line 3, in ValidHandle
...
@@ -662,12 +662,12 @@ POINTs among other stuff::
...
@@ -662,12 +662,12 @@ POINTs among other stuff::
>>> from ctypes import *
>>> from ctypes import *
>>> class POINT(Structure):
>>> class POINT(Structure):
... _fields_ = ("x", c_int), ("y", c_int)
...
_fields_ = ("x", c_int), ("y", c_int)
...
...
>>> class MyStruct(Structure):
>>> class MyStruct(Structure):
... _fields_ = [("a", c_int),
...
_fields_ = [("a", c_int),
... ("b", c_float),
...
("b", c_float),
... ("point_array", POINT * 4)]
...
("point_array", POINT * 4)]
>>>
>>>
>>> print len(MyStruct().point_array)
>>> print len(MyStruct().point_array)
4
4
...
@@ -1028,7 +1028,7 @@ Here is what we get on Windows::
...
@@ -1028,7 +1028,7 @@ Here is what we get on Windows::
It is funny to see that on linux the sort function seems to work much more
It is funny to see that on linux the sort function seems to work much more
efficiently, it is doing less comparisons::
efficiently, it is doing less comparisons::
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func)
# doctest: +LINUX
py_cmp_func 5 1
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 7 33
...
@@ -1151,9 +1151,9 @@ access violation or whatever, so it's better to break out of the loop when we
...
@@ -1151,9 +1151,9 @@ access violation or whatever, so it's better to break out of the loop when we
hit the NULL entry::
hit the NULL entry::
>>> for item in table:
>>> for item in table:
... print item.name, item.size
...
print item.name, item.size
... if item.name is None:
...
if item.name is None:
... break
...
break
...
...
__hello__ 104
__hello__ 104
__phello__ -104
__phello__ -104
...
...
Doc/library/getopt.rst
View file @
12d547a8
...
@@ -129,7 +129,7 @@ In a script, typical usage is something like this::
...
@@ -129,7 +129,7 @@ In a script, typical usage is something like this::
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
except getopt.GetoptError as err:
# print help information and exit:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
print str(err)
# will print something like "option -a not recognized"
usage()
usage()
sys.exit(2)
sys.exit(2)
output = None
output = None
...
...
Doc/library/htmlparser.rst
View file @
12d547a8
...
@@ -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
...
...
Doc/library/locale.rst
View file @
12d547a8
...
@@ -481,13 +481,13 @@ The :mod:`locale` module defines the following exception and functions:
...
@@ -481,13 +481,13 @@ The :mod:`locale` module defines the following exception and functions:
Example::
Example::
>>> import locale
>>> import locale
>>> loc = locale.getlocale() # get current locale
>>> loc = locale.getlocale()
# get current locale
# use German locale; name might vary with platform
# use German locale; name might vary with platform
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
>>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
>>> locale.strcoll('f\xe4n', 'foo')
# compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, '')
# use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, 'C')
# use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
>>> locale.setlocale(locale.LC_ALL, loc)
# restore saved locale
Background, details, hints, tips and caveats
Background, details, hints, tips and caveats
...
...
Doc/library/mailcap.rst
View file @
12d547a8
...
@@ -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'})
Doc/library/mmap.rst
View file @
12d547a8
...
@@ -140,7 +140,7 @@ memory but does not update the underlying file.
...
@@ -140,7 +140,7 @@ memory but does not update the underlying file.
pid = os.fork()
pid = os.fork()
if pid == 0: # In a child process
if pid == 0:
# In a child process
mm.seek(0)
mm.seek(0)
print mm.readline()
print mm.readline()
...
...
Doc/library/multiprocessing.rst
View file @
12d547a8
...
@@ -2352,8 +2352,8 @@ Explicitly pass resources to child processes
...
@@ -2352,8 +2352,8 @@ Explicitly pass resources to child processes
...
do
something
using
"lock"
...
...
do
something
using
"lock"
...
if
__name__
==
'__main__'
:
if
__name__
==
'__main__'
:
lock
=
Lock
()
lock
=
Lock
()
for
i
in
range
(
10
):
for
i
in
range
(
10
):
Process
(
target
=
f
).
start
()
Process
(
target
=
f
).
start
()
should
be
rewritten
as
::
should
be
rewritten
as
::
...
@@ -2364,8 +2364,8 @@ Explicitly pass resources to child processes
...
@@ -2364,8 +2364,8 @@ Explicitly pass resources to child processes
...
do
something
using
"l"
...
...
do
something
using
"l"
...
if
__name__
==
'__main__'
:
if
__name__
==
'__main__'
:
lock
=
Lock
()
lock
=
Lock
()
for
i
in
range
(
10
):
for
i
in
range
(
10
):
Process
(
target
=
f
,
args
=(
lock
,)).
start
()
Process
(
target
=
f
,
args
=(
lock
,)).
start
()
Beware
of
replacing
:
data
:`
sys
.
stdin
`
with
a
"file like object"
Beware
of
replacing
:
data
:`
sys
.
stdin
`
with
a
"file like object"
...
...
Doc/library/optparse.rst
View file @
12d547a8
...
@@ -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,9 +1827,9 @@ arguments::
...
@@ -1827,9 +1827,9 @@ 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)
..
_optparse-extending-optparse:
..
_optparse-extending-optparse:
...
...
Doc/library/re.rst
View file @
12d547a8
...
@@ -1120,15 +1120,15 @@ does by default).
...
@@ -1120,15 +1120,15 @@ does by default).
For example::
For example::
>>> re.match("c", "abcdef") # No match
>>> re.match("c", "abcdef")
# No match
>>> re.search("c", "abcdef") # Match
>>> re.search("c", "abcdef")
# Match
<_sre.SRE_Match object at ...>
<_sre.SRE_Match object at ...>
Regular expressions beginning with ``'^'`` can be used with :func:`search` to
Regular expressions beginning with ``'^'`` can be used with :func:`search` to
restrict the match at the beginning of the string::
restrict the match at the beginning of the string::
>>> re.match("c", "abcdef") # No match
>>> re.match("c", "abcdef")
# No match
>>> re.search("^c", "abcdef") # No match
>>> re.search("^c", "abcdef")
# No match
>>> re.search("^a", "abcdef") # Match
>>> re.search("^a", "abcdef") # Match
<_sre.SRE_Match object at ...>
<_sre.SRE_Match object at ...>
...
@@ -1209,9 +1209,9 @@ a function to "munge" text, or randomize the order of all the characters
...
@@ -1209,9 +1209,9 @@ a function to "munge" text, or randomize the order of all the characters
in each word of a sentence except for the first and last characters::
in each word of a sentence except for the first and last characters::
>>> def repl(m):
>>> def repl(m):
... inner_word = list(m.group(2))
...
inner_word = list(m.group(2))
... random.shuffle(inner_word)
...
random.shuffle(inner_word)
... return m.group(1) + "".join(inner_word) + m.group(3)
...
return m.group(1) + "".join(inner_word) + m.group(3)
>>> text = "Professor Abdolmalek, please report your absences promptly."
>>> text = "Professor Abdolmalek, please report your absences promptly."
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
...
...
Doc/library/ssl.rst
View file @
12d547a8
...
@@ -1452,7 +1452,7 @@ should use the following idiom::
...
@@ -1452,7 +1452,7 @@ should use the following idiom::
except ImportError:
except ImportError:
pass
pass
else:
else:
... # do something that requires SSL support
...
# do something that requires SSL support
Client-side operation
Client-side operation
^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^
...
...
Doc/library/string.rst
View file @
12d547a8
...
@@ -262,12 +262,12 @@ does an index lookup using :func:`__getitem__`.
...
@@ -262,12 +262,12 @@ does an index lookup using :func:`__getitem__`.
Some simple format string examples::
Some simple format string examples::
"First, thou shalt count to {0}" # References first positional argument
"First, thou shalt count to {0}"
# References first positional argument
"Bring me a {}" # Implicitly references the first positional argument
"Bring me a {}"
# Implicitly references the first positional argument
"From {} to {}" # Same as "From {0} to {1}"
"From {} to {}"
# Same as "From {0} to {1}"
"My quest is {name}" # References keyword argument 'name'
"My quest is {name}"
# References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Weight in tons {0.weight}"
# 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.
"Units destroyed: {players[0]}"
# First element of keyword argument 'players'.
The *conversion* field causes a type coercion before formatting. Normally, the
The *conversion* field causes a type coercion before formatting. Normally, the
job of formatting a value is done by the :meth:`__format__` method of the value
job of formatting a value is done by the :meth:`__format__` method of the value
...
...
Doc/library/threading.rst
View file @
12d547a8
...
@@ -778,7 +778,7 @@ For example::
...
@@ -778,7 +778,7 @@ For example::
print "hello, world"
print "hello, world"
t = Timer(30.0, hello)
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
t.start()
# after 30 seconds, "hello, world" will be printed
.. class:: Timer(interval, function, args=[], kwargs={})
.. class:: Timer(interval, function, args=[], kwargs={})
...
...
Doc/library/unittest.rst
View file @
12d547a8
...
@@ -115,19 +115,19 @@ Here is a short script to test three string methods::
...
@@ -115,19 +115,19 @@ Here is a short script to test three string methods::
class TestStringMethods(unittest.TestCase):
class TestStringMethods(unittest.TestCase):
def test_upper(self):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
def test_split(self):
s = 'hello world'
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
with self.assertRaises(TypeError):
s.split(2)
s.split(2)
if __name__ == '__main__':
if __name__ == '__main__':
unittest.main()
unittest.main()
...
...
Doc/library/wsgiref.rst
View file @
12d547a8
...
@@ -418,8 +418,8 @@ Paste" library.
...
@@ -418,8 +418,8 @@ Paste" library.
# Our callable object which is intentionally not compliant to the
# Our callable object which is intentionally not compliant to the
# standard, so the validator is going to break
# standard, so the validator is going to break
def simple_app(environ, start_response):
def simple_app(environ, start_response):
status = '200 OK' # HTTP Status
status = '200 OK'
# HTTP Status
headers = [('Content-type', 'text/plain')] # HTTP Headers
headers = [('Content-type', 'text/plain')]
# HTTP Headers
start_response(status, headers)
start_response(status, headers)
# This is going to break because we need to return a list, and
# This is going to break because we need to return a list, and
...
@@ -714,8 +714,8 @@ This is a working "Hello World" WSGI application::
...
@@ -714,8 +714,8 @@ This is a working "Hello World" WSGI application::
# is a dictionary containing CGI-style envrironment variables and the
# is a dictionary containing CGI-style envrironment variables and the
# second variable is the callable object (see PEP 333).
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):
def hello_world_app(environ, start_response):
status = '200 OK' # HTTP Status
status = '200 OK'
# HTTP Status
headers = [('Content-type', 'text/plain')] # HTTP Headers
headers = [('Content-type', 'text/plain')]
# HTTP Headers
start_response(status, headers)
start_response(status, headers)
# The returned object is going to be printed
# The returned object is going to be printed
...
...
Doc/library/xml.dom.minidom.rst
View file @
12d547a8
...
@@ -33,10 +33,10 @@ DOM applications typically start by parsing some XML into a DOM. With
...
@@ -33,10 +33,10 @@ DOM applications typically start by parsing some XML into a DOM. With
from
xml
.
dom
.
minidom
import
parse
,
parseString
from
xml
.
dom
.
minidom
import
parse
,
parseString
dom1
=
parse
(
'c:\\temp\\mydata.xml'
)
#
parse
an
XML
file
by
name
dom1
=
parse
(
'c:\\temp\\mydata.xml'
)
#
parse
an
XML
file
by
name
datasource
=
open
(
'c:\\temp\\mydata.xml'
)
datasource
=
open
(
'c:\\temp\\mydata.xml'
)
dom2
=
parse
(
datasource
)
#
parse
an
open
file
dom2
=
parse
(
datasource
)
#
parse
an
open
file
dom3
=
parseString
(
'<myxml>Some data<empty/> some more data</myxml>'
)
dom3
=
parseString
(
'<myxml>Some data<empty/> some more data</myxml>'
)
...
...
Doc/library/xml.etree.elementtree.rst
View file @
12d547a8
...
@@ -129,7 +129,7 @@ As an :class:`Element`, ``root`` has a tag and a dictionary of attributes::
...
@@ -129,7 +129,7 @@ As an :class:`Element`, ``root`` has a tag and a dictionary of attributes::
It also has children nodes over which we can iterate::
It also has children nodes over which we can iterate::
>>> for child in root:
>>> for child in root:
... print child.tag, child.attrib
...
print child.tag, child.attrib
...
...
country {'name': 'Liechtenstein'}
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Singapore'}
...
@@ -148,7 +148,7 @@ the sub-tree below it (its children, their children, and so on). For example,
...
@@ -148,7 +148,7 @@ the sub-tree below it (its children, their children, and so on). For example,
:meth:`Element.iter`::
:meth:`Element.iter`::
>>> for neighbor in root.iter('neighbor'):
>>> for neighbor in root.iter('neighbor'):
... print neighbor.attrib
...
print neighbor.attrib
...
...
{'name': 'Austria', 'direction': 'E'}
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Switzerland', 'direction': 'W'}
...
@@ -162,9 +162,9 @@ with a particular tag, and :attr:`Element.text` accesses the element's text
...
@@ -162,9 +162,9 @@ with a particular tag, and :attr:`Element.text` accesses the element's text
content. :meth:`Element.get` accesses the element's attributes::
content. :meth:`Element.get` accesses the element's attributes::
>>> for country in root.findall('country'):
>>> for country in root.findall('country'):
... rank = country.find('rank').text
...
rank = country.find('rank').text
... name = country.get('name')
...
name = country.get('name')
... print name, rank
...
print name, rank
...
...
Liechtenstein 1
Liechtenstein 1
Singapore 4
Singapore 4
...
@@ -188,9 +188,9 @@ Let's say we want to add one to each country's rank, and add an ``updated``
...
@@ -188,9 +188,9 @@ Let's say we want to add one to each country's rank, and add an ``updated``
attribute to the rank element::
attribute to the rank element::
>>> for rank in root.iter('rank'):
>>> for rank in root.iter('rank'):
... new_rank = int(rank.text) + 1
...
new_rank = int(rank.text) + 1
... rank.text = str(new_rank)
...
rank.text = str(new_rank)
... rank.set('updated', 'yes')
...
rank.set('updated', 'yes')
...
...
>>> tree.write('output.xml')
>>> tree.write('output.xml')
...
@@ -226,9 +226,9 @@ We can remove elements using :meth:`Element.remove`. Let's say we want to
...
@@ -226,9 +226,9 @@ We can remove elements using :meth:`Element.remove`. Let's say we want to
remove all countries with a rank higher than 50::
remove all countries with a rank higher than 50::
>>> for country in root.findall('country'):
>>> for country in root.findall('country'):
... rank = int(country.find('rank').text)
...
rank = int(country.find('rank').text)
... if rank > 50:
...
if rank > 50:
... root.remove(country)
...
root.remove(country)
...
...
>>> tree.write('output.xml')
>>> tree.write('output.xml')
...
@@ -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:
...
...
Doc/library/xmlrpclib.rst
View file @
12d547a8
...
@@ -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)
...
...
Doc/reference/expressions.rst
View file @
12d547a8
...
@@ -761,7 +761,7 @@ A consequence of this is that although the ``*expression`` syntax may appear
...
@@ -761,7 +761,7 @@ A consequence of this is that although the ``*expression`` syntax may appear
(and the ``**expression`` argument, if any -- see below). So::
(and the ``**expression`` argument, if any -- see below). So::
>>> def f(a, b):
>>> def f(a, b):
... print a, b
...
print a, b
...
...
>>> f(b=1, *(2,))
>>> f(b=1, *(2,))
2 1
2 1
...
...
Doc/reference/simple_stmts.rst
View file @
12d547a8
...
@@ -306,12 +306,12 @@ program:
...
@@ -306,12 +306,12 @@ program:
The
simple
form
,
``
assert
expression
``,
is
equivalent
to
::
The
simple
form
,
``
assert
expression
``,
is
equivalent
to
::
if
__debug__
:
if
__debug__
:
if
not
expression
:
raise
AssertionError
if
not
expression
:
raise
AssertionError
The
extended
form
,
``
assert
expression1
,
expression2
``,
is
equivalent
to
::
The
extended
form
,
``
assert
expression1
,
expression2
``,
is
equivalent
to
::
if
__debug__
:
if
__debug__
:
if
not
expression1
:
raise
AssertionError
(
expression2
)
if
not
expression1
:
raise
AssertionError
(
expression2
)
..
index
::
..
index
::
single
:
__debug__
single
:
__debug__
...
...
Doc/tutorial/appendix.rst
View file @
12d547a8
...
@@ -92,7 +92,7 @@ in the script::
...
@@ -92,7 +92,7 @@ in the script::
filename = os.environ.get('PYTHONSTARTUP')
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
if filename and os.path.isfile(filename):
with open(filename) as fobj:
with open(filename) as fobj:
startup_file = fobj.read()
startup_file = fobj.read()
exec(startup_file)
exec(startup_file)
...
...
Doc/tutorial/classes.rst
View file @
12d547a8
...
@@ -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)
...
@@ -670,7 +675,7 @@ will do nicely::
...
@@ -670,7 +675,7 @@ will do nicely::
class Employee:
class Employee:
pass
pass
john = Employee() # Create an empty employee record
john = Employee()
# Create an empty employee record
# Fill the fields of the record
# Fill the fields of the record
john.name = 'John Doe'
john.name = 'John Doe'
...
@@ -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
...
...
Doc/tutorial/controlflow.rst
View file @
12d547a8
...
@@ -284,7 +284,7 @@ You can see it if you really want to using :keyword:`print`::
...
@@ -284,7 +284,7 @@ You can see it if you really want to using :keyword:`print`::
It is simple to write a function that returns a list of the numbers of the
It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it::
Fibonacci series, instead of printing it::
>>> def fib2(n): # return Fibonacci series up to n
>>> def fib2(n):
# return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... """Return a list containing the Fibonacci series up to n."""
... result = []
... result = []
... a, b = 0, 1
... a, b = 0, 1
...
...
Doc/tutorial/errors.rst
View file @
12d547a8
...
@@ -180,14 +180,14 @@ One may also instantiate an exception first before raising it and add any
...
@@ -180,14 +180,14 @@ One may also instantiate an exception first before raising it and add any
attributes to it as desired. ::
attributes to it as desired. ::
>>> try:
>>> try:
... raise Exception('spam', 'eggs')
...
raise Exception('spam', 'eggs')
... except Exception as inst:
... except Exception as inst:
... print type(inst) # the exception instance
...
print type(inst) # the exception instance
... print inst.args # arguments stored in .args
...
print inst.args # arguments stored in .args
... print inst # __str__ allows args to be printed directly
...
print inst # __str__ allows args to be printed directly
... x, y = inst.args
...
x, y = inst.args
... print 'x =', x
...
print 'x =', x
... print 'y =', y
...
print 'y =', y
...
...
<type 'exceptions.Exception'>
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
...
...
Doc/tutorial/inputoutput.rst
View file @
12d547a8
...
@@ -326,10 +326,10 @@ beginning of the file as the reference point. ::
...
@@ -326,10 +326,10 @@ beginning of the file as the reference point. ::
>>> f = open('workfile', 'r+')
>>> f = open('workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.write('0123456789abcdef')
>>> f.seek(5) # Go to the 6th byte in the file
>>> f.seek(5)
# Go to the 6th byte in the file
>>> f.read(1)
>>> f.read(1)
'5'
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.seek(-3, 2)
# Go to the 3rd byte before the end
>>> f.read(1)
>>> f.read(1)
'd'
'd'
...
...
Doc/tutorial/introduction.rst
View file @
12d547a8
...
@@ -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.'
...
@@ -280,11 +280,11 @@ makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
...
@@ -280,11 +280,11 @@ makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
Slice indices have useful defaults; an omitted first index defaults to zero, an
Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the size of the string being sliced. ::
omitted second index defaults to the size of the string being sliced. ::
>>> word[:2] # character from the beginning to position 2 (excluded)
>>> word[:2]
# character from the beginning to position 2 (excluded)
'Py'
'Py'
>>> word[4:] # characters from position 4 (included) to the end
>>> word[4:]
# characters from position 4 (included) to the end
'on'
'on'
>>> word[-2:] # characters from the second-last (included) to the end
>>> word[-2:]
# characters from the second-last (included) to the end
'on'
'on'
One way to remember how slices work is to think of the indices as pointing
One way to remember how slices work is to think of the indices as pointing
...
...
Doc/tutorial/modules.rst
View file @
12d547a8
...
@@ -33,7 +33,7 @@ called :file:`fibo.py` in the current directory with the following contents::
...
@@ -33,7 +33,7 @@ called :file:`fibo.py` in the current directory with the following contents::
print
b
,
print
b
,
a
,
b
=
b
,
a
+
b
a
,
b
=
b
,
a
+
b
def
fib2
(
n
):
#
return
Fibonacci
series
up
to
n
def
fib2
(
n
):
#
return
Fibonacci
series
up
to
n
result
=
[]
result
=
[]
a
,
b
=
0
,
1
a
,
b
=
0
,
1
while
b
<
n
:
while
b
<
n
:
...
...
Doc/tutorial/stdlib.rst
View file @
12d547a8
...
@@ -283,7 +283,7 @@ file::
...
@@ -283,7 +283,7 @@ file::
with self.assertRaises(TypeError):
with self.assertRaises(TypeError):
average(20, 30, 70)
average(20, 30, 70)
unittest.main() # Calling from the command line invokes all tests
unittest.main()
# Calling from the command line invokes all tests
.. _tut-batteries-included:
.. _tut-batteries-included:
...
...
Doc/tutorial/stdlib2.rst
View file @
12d547a8
...
@@ -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)
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment