Partial py3k-ification of Doc/library/: convert has_key references into either 'k in d' or __contains__; normalize raise statements; convert print statements into print function calls.

This commit is contained in:
Collin Winter 2007-09-01 23:34:30 +00:00
parent 2ac0121305
commit c79461b164
31 changed files with 80 additions and 86 deletions

View file

@ -105,6 +105,11 @@ Once instantiated, hash, btree and record objects support the same methods as
dictionaries. In addition, they support the methods listed below.
.. describe:: key in bsddbobject
Return ``True`` if the DB file contains the argument as a key.
.. method:: bsddbobject.close()
Close the underlying file. The object can no longer be accessed. Since there
@ -119,11 +124,6 @@ dictionaries. In addition, they support the methods listed below.
returned is different for different file formats.
.. method:: bsddbobject.has_key(key)
Return ``1`` if the DB file contains the argument as a key.
.. method:: bsddbobject.set_location(key)
Set the cursor to the item indicated by *key* and return a tuple containing the
@ -169,7 +169,8 @@ Example::
>>> import bsddb
>>> db = bsddb.btopen('/tmp/spam.db', 'c')
>>> for i in range(10): db['%d'%i] = '%d'% (i*i)
>>> for i in range(10):
... db[str(i)] = '%d' % (i*i)
...
>>> db['3']
'9'
@ -186,7 +187,7 @@ Example::
>>> db.previous()
('1', '1')
>>> for k, v in db.iteritems():
... print k, v
... print(k, v)
0 0
1 1
2 4

View file

@ -91,11 +91,11 @@ various environment variables set according to the CGI standard). Since it may
consume standard input, it should be instantiated only once.
The :class:`FieldStorage` instance can be indexed like a Python dictionary, and
also supports the standard dictionary methods :meth:`has_key` and :meth:`keys`.
The built-in :func:`len` is also supported. Form fields containing empty
strings are ignored and do not appear in the dictionary; to keep such values,
provide a true value for the optional *keep_blank_values* keyword parameter when
creating the :class:`FieldStorage` instance.
also supports the standard dictionary methods :meth:`__contains__` and
:meth:`keys`. The built-in :func:`len` is also supported. Form fields
containing empty strings are ignored and do not appear in the dictionary; to
keep such values, provide a true value for the optional *keep_blank_values*
keyword parameter when creating the :class:`FieldStorage` instance.
For instance, the following code (which assumes that the
:mailheader:`Content-Type` header and blank line have already been printed)
@ -103,7 +103,7 @@ checks that the fields ``name`` and ``addr`` are both set to a non-empty
string::
form = cgi.FieldStorage()
if not (form.has_key("name") and form.has_key("addr")):
if not ("name" in form and "addr" in form):
print "<H1>Error</H1>"
print "Please fill in the name and addr fields."
return

View file

@ -200,7 +200,7 @@ included in the mapping interface.
No exception is raised if the named field isn't present in the headers.
.. method:: Message.has_key(name)
.. method:: Message.__contains__(name)
Return true if the message contains a header field named *name*, otherwise
return false.

View file

@ -122,10 +122,10 @@ This code is intended to be read, not executed. However, it does work
return m
def determine_parent(globals):
if not globals or not globals.has_key("__name__"):
if not globals or not "__name__" in globals:
return None
pname = globals['__name__']
if globals.has_key("__path__"):
if "__path__" in globals:
parent = sys.modules[pname]
assert globals is parent.__dict__
return parent
@ -156,7 +156,7 @@ This code is intended to be read, not executed. However, it does work
parent = None
q = import_module(head, qname, parent)
if q: return q, tail
raise ImportError, "No module named " + qname
raise ImportError("No module named " + qname)
def load_tail(q, tail):
m = q
@ -167,7 +167,7 @@ This code is intended to be read, not executed. However, it does work
mname = "%s.%s" % (m.__name__, head)
m = import_module(head, mname, m)
if not m:
raise ImportError, "No module named " + mname
raise ImportError("No module named " + mname)
return m
def ensure_fromlist(m, fromlist, recursive=0):
@ -185,7 +185,7 @@ This code is intended to be read, not executed. However, it does work
subname = "%s.%s" % (m.__name__, sub)
submod = import_module(sub, subname, m)
if not submod:
raise ImportError, "No module named " + subname
raise ImportError("No module named " + subname)
def import_module(partname, fqname, parent):
try:

View file

@ -188,8 +188,7 @@ the corresponding message is subsequently removed.
subclass.
.. method:: Mailbox.has_key(key)
Mailbox.__contains__(key)
.. method:: Mailbox.__contains__(key)
Return ``True`` if *key* corresponds to a message, ``False`` otherwise.

View file

@ -260,7 +260,7 @@ A :class:`Message` instance has the following methods:
:class:`Message` instances also support a limited mapping interface. In
particular: ``m[name]`` is like ``m.getheader(name)`` but raises :exc:`KeyError`
if there is no matching header; and ``len(m)``, ``m.get(name[, default])``,
``m.has_key(name)``, ``m.keys()``, ``m.values()`` ``m.items()``, and
``m.__contains__(name)``, ``m.keys()``, ``m.values()`` ``m.items()``, and
``m.setdefault(name[, default])`` act as expected, with the one difference
that :meth:`setdefault` uses an empty string as the default value.
:class:`Message` instances also support the mapping writable interface ``m[name]

View file

@ -131,7 +131,7 @@ object)::
# such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = d.has_key(key) # true if the key exists
flag = key in d # true if the key exists
klist = d.keys() # a list of all existing keys (slow!)
# as d was opened WITHOUT writeback=True, beware:

View file

@ -157,5 +157,5 @@ provided by this module. ::
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise Error, errors
raise Error(errors)

View file

@ -144,7 +144,7 @@ be sent, and the handler raises an exception. ::
def handler(signum, frame):
print 'Signal handler called with signal', signum
raise IOError, "Couldn't open device!"
raise IOError("Couldn't open device!")
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)

View file

@ -157,10 +157,10 @@ Example::
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
print('Skipping %s' % pathname)
def visitfile(file):
print 'visiting', file
print('visiting', file)
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)

View file

@ -1032,8 +1032,8 @@ formats in the string *must* include a parenthesised mapping key into that
dictionary inserted immediately after the ``'%'`` character. The mapping key
selects the value to be formatted from the mapping. For example::
>>> print '%(language)s has %(#)03d quote types.' % \
{'language': "Python", "#": 2}
>>> print('%(language)s has %(#)03d quote types.' %
{'language': "Python", "#": 2})
Python has 002 quote types.
In this case no ``*`` specifiers may occur in a format (since they require a
@ -1805,10 +1805,6 @@ types should support too):
*default* is not given, it defaults to ``None``, so that this method never
raises a :exc:`KeyError`.
.. method:: dict.has_key(key)
``d.has_key(key)`` is equivalent to ``key in d``, but deprecated.
.. method:: dict.items()
Return a copy of the dictionary's list of ``(key, value)`` pairs.
@ -1923,7 +1919,7 @@ Files have the following methods:
with open("hello.txt") as f:
for line in f:
print line
print(line)
In older versions of Python, you would have needed to do this to get the same
effect::
@ -1931,7 +1927,7 @@ Files have the following methods:
f = open("hello.txt")
try:
for line in f:
print line
print(line)
finally:
f.close()

View file

@ -45,7 +45,7 @@ Example usage::
output = StringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'
print('Second line.', file=output)
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
@ -111,7 +111,7 @@ Example usage::
output = cStringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'
print('Second line.', file=output)
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'

View file

@ -284,11 +284,11 @@ A more realistic example would look like this::
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
print("Child was terminated by signal", -retcode, file=sys.stderr)
else:
print >>sys.stderr, "Child returned", retcode
print("Child returned", retcode, file=sys.stderr)
except OSError as e:
print >>sys.stderr, "Execution failed:", e
print("Execution failed:", e, file=sys.stderr)
Replacing os.spawn\*

View file

@ -601,13 +601,13 @@ How to read a gzip compressed tar archive and display some member information::
import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
print tarinfo.name, "is", tarinfo.size, "bytes in size and is",
print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="")
if tarinfo.isreg():
print "a regular file."
print("a regular file.")
elif tarinfo.isdir():
print "a directory."
print("a directory.")
else:
print "something else."
print("something else.")
tar.close()
How to create a tar archive with faked information::

View file

@ -234,5 +234,5 @@ A simple example illustrating typical use::
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
print(tn.read_all())

View file

@ -307,7 +307,7 @@ The :mod:`test.test_support` module defines the following functions:
Example use::
with captured_stdout() as s:
print "hello"
print("hello")
assert s.getvalue() == "hello"

View file

@ -64,8 +64,8 @@ indentation from strings that have unwanted whitespace to the left of the text.
hello
world
'''
print repr(s) # prints ' hello\n world\n '
print repr(dedent(s)) # prints 'hello\n world\n'
print(repr(s)) # prints ' hello\n world\n '
print(repr(dedent(s))) # prints 'hello\n world\n'
.. class:: TextWrapper(...)

View file

@ -135,7 +135,7 @@ In addition to these methods, lock objects can also be used via the
a_lock = thread.allocate_lock()
with a_lock:
print "a_lock is locked while this executes"
print("a_lock is locked while this executes")
**Caveats:**

View file

@ -683,7 +683,7 @@ exactly the same as the interval specified by the user.
For example::
def hello():
print "hello, world"
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
@ -721,5 +721,5 @@ Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
some_rlock = threading.RLock()
with some_rlock:
print "some_rlock is locked while this executes"
print("some_rlock is locked while this executes")

View file

@ -196,13 +196,13 @@ attributes. ::
... pass
... """
>>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
>>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
17.09 usec/pass
>>> s = """\
... if hasattr(str, '__bool__'): pass
... """
>>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
>>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
4.85 usec/pass
>>> s = """\
... try:
@ -211,13 +211,13 @@ attributes. ::
... pass
... """
>>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
>>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
1.97 usec/pass
>>> s = """\
... if hasattr(int, '__bool__'): pass
... """
>>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
>>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
3.15 usec/pass
To give the :mod:`timeit` module access to functions you define, you can pass a
@ -225,12 +225,10 @@ To give the :mod:`timeit` module access to functions you define, you can pass a
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
L = [i for i in range(100)]
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
print(t.timeit())

View file

@ -505,7 +505,7 @@ Tix Commands
import Tix
root = Tix.Tk()
print root.tix_configure()
print(root.tix_configure())
.. method:: tixCommand.tix_configure([cnf,] **kw)

View file

@ -184,7 +184,7 @@ A Simple Hello World Program
class Application(Frame):
def say_hi(self):
print "hi there, everyone!"
print("hi there, everyone!")
def createWidgets(self):
self.QUIT = Button(self)
@ -441,7 +441,7 @@ back will contain the name of the synonym and the "real" option (such as
Example::
>>> print fred.config()
>>> print(fred.config())
{'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
Of course, the dictionary printed will include all the options available and
@ -560,8 +560,8 @@ For example::
self.print_contents)
def print_contents(self, event):
print "hi. contents of entry is now ---->", \
self.contents.get()
print("hi. contents of entry is now ---->",
self.contents.get())
The Window Manager
@ -633,7 +633,7 @@ callback
This is any Python function that takes no arguments. For example::
def print_it():
print "hi there"
print("hi there")
fred["command"] = print_it
color

View file

@ -147,12 +147,12 @@ module. ::
try:
exec(source, envdir)
except:
print "Exception in user code:"
print '-'*60
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print '-'*60
print("-"*60)
envdir = {}
while 1:
while True:
run_user_code(envdir)

View file

@ -438,14 +438,14 @@ containing parameters::
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.read()
>>> print(f.read())
The following example uses the ``POST`` method instead::
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
>>> print(f.read())
The following example uses an explicitly specified HTTP proxy, overriding
environment settings::

View file

@ -834,7 +834,7 @@ it::
>>> import urllib2
>>> f = urllib2.urlopen('http://www.python.org/')
>>> print f.read(100)
>>> print(f.read(100))
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<?xml-stylesheet href="./css/ht2html
@ -846,7 +846,7 @@ installation supports SSL. ::
>>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',
... data='This data is passed to stdin of the CGI')
>>> f = urllib2.urlopen(req)
>>> print f.read()
>>> print(f.read())
Got Data: "This data is passed to stdin of the CGI"
The code for the sample CGI used in the above example is::
@ -854,7 +854,7 @@ The code for the sample CGI used in the above example is::
#!/usr/bin/env python
import sys
data = sys.stdin.read()
print 'Content-type: text-plain\n\nGot Data: "%s"' % data
print('Content-type: text-plain\n\nGot Data: "%s"' % data)
Use of Basic HTTP Authentication::

View file

@ -236,7 +236,7 @@ If the referent no longer exists, calling the reference object returns
:const:`None`::
>>> del o, o2
>>> print r()
>>> print(r())
None
Testing that a weak reference object is still live should be done using the
@ -247,9 +247,9 @@ a reference object should follow this pattern::
o = r()
if o is None:
# referent has been garbage collected
print "Object has been deallocated; can't frobnicate."
print("Object has been deallocated; can't frobnicate.")
else:
print "Object is still live!"
print("Object is still live!")
o.do_something_useful()
Using a separate test for "liveness" creates race conditions in threaded

View file

@ -244,7 +244,7 @@ request. (E.g., using the :func:`shift_path_info` function from
from wsgiref.simple_server import make_server, demo_app
httpd = make_server('', 8000, demo_app)
print "Serving HTTP on port 8000..."
print("Serving HTTP on port 8000...")
# Respond to requests until process is killed
httpd.serve_forever()

View file

@ -272,5 +272,5 @@ Here is an example of how you would catch one of these exceptions::
try:
p.pack_double(8.01)
except xdrlib.ConversionError as instance:
print 'packing the double failed:', instance.msg
print('packing the double failed:', instance.msg)

View file

@ -278,10 +278,10 @@ elements with no subelements will test as ``False``. ::
element = root.find('foo')
if not element: # careful!
print "element not found, or element has no subelements"
print("element not found, or element has no subelements")
if element is None:
print "element not found"
print("element not found")
.. _elementtree-elementtree-objects:

View file

@ -42,7 +42,7 @@ or as base classes.
will be wrapped in double-quotes. The resulting string can be used directly
as an attribute value::
>>> print "<element attr=%s>" % quoteattr("ab ' cd \" ef")
>>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
<element attr="ab ' cd &quot; ef">
This function is useful when generating attribute values for HTML or any SGML

View file

@ -371,12 +371,12 @@ Example of Client Usage
# server = ServerProxy("http://localhost:8000") # local server
server = ServerProxy("http://betty.userland.com")
print server
print(server)
try:
print server.examples.getStateName(41)
print(server.examples.getStateName(41))
except Error as v:
print "ERROR", v
print("ERROR", v)
To access an XML-RPC server through a proxy, you need to define a custom
transport. The following example, written by NoboNobo, shows how:
@ -404,5 +404,5 @@ transport. The following example, written by NoboNobo, shows how:
p = ProxiedTransport()
p.set_proxy('proxy-server:8080')
server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
print server.currentTime.getCurrentTime()
print(server.currentTime.getCurrentTime())