diff options
author | Collin Winter <collinw@gmail.com> | 2007-09-01 23:34:30 (GMT) |
---|---|---|
committer | Collin Winter <collinw@gmail.com> | 2007-09-01 23:34:30 (GMT) |
commit | c79461b1648c9209c3652184572a17eef0a76202 (patch) | |
tree | 47c6238c8c47c4881f6f0523ea86d201cea1fc94 /Doc | |
parent | 2ac012130549b1ef51ebce11148d01eaca1a7033 (diff) | |
download | cpython-c79461b1648c9209c3652184572a17eef0a76202.zip cpython-c79461b1648c9209c3652184572a17eef0a76202.tar.gz cpython-c79461b1648c9209c3652184572a17eef0a76202.tar.bz2 |
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.
Diffstat (limited to 'Doc')
31 files changed, 80 insertions, 86 deletions
diff --git a/Doc/library/bsddb.rst b/Doc/library/bsddb.rst index c5c6276..aff1d5b 100644 --- a/Doc/library/bsddb.rst +++ b/Doc/library/bsddb.rst @@ -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 diff --git a/Doc/library/cgi.rst b/Doc/library/cgi.rst index 98166e8..d2b88aa 100644 --- a/Doc/library/cgi.rst +++ b/Doc/library/cgi.rst @@ -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 diff --git a/Doc/library/email.message.rst b/Doc/library/email.message.rst index 871a5f8..e494a71 100644 --- a/Doc/library/email.message.rst +++ b/Doc/library/email.message.rst @@ -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. diff --git a/Doc/library/imputil.rst b/Doc/library/imputil.rst index 92eeda2..eff1cb9 100644 --- a/Doc/library/imputil.rst +++ b/Doc/library/imputil.rst @@ -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: diff --git a/Doc/library/mailbox.rst b/Doc/library/mailbox.rst index ce8dc59..cfd1ebe 100644 --- a/Doc/library/mailbox.rst +++ b/Doc/library/mailbox.rst @@ -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. diff --git a/Doc/library/rfc822.rst b/Doc/library/rfc822.rst index da9f536..bd8c9a2 100644 --- a/Doc/library/rfc822.rst +++ b/Doc/library/rfc822.rst @@ -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] diff --git a/Doc/library/shelve.rst b/Doc/library/shelve.rst index 8aa2cf7..262b4a4 100644 --- a/Doc/library/shelve.rst +++ b/Doc/library/shelve.rst @@ -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: diff --git a/Doc/library/shutil.rst b/Doc/library/shutil.rst index 2e3fafe..927ddb0 100644 --- a/Doc/library/shutil.rst +++ b/Doc/library/shutil.rst @@ -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) diff --git a/Doc/library/signal.rst b/Doc/library/signal.rst index 54cce53..94f305c 100644 --- a/Doc/library/signal.rst +++ b/Doc/library/signal.rst @@ -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) diff --git a/Doc/library/stat.rst b/Doc/library/stat.rst index 430bb23..d4eae5d 100644 --- a/Doc/library/stat.rst +++ b/Doc/library/stat.rst @@ -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) diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 9ce63d9..77a8411 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -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() diff --git a/Doc/library/stringio.rst b/Doc/library/stringio.rst index 4736fc3..192e310 100644 --- a/Doc/library/stringio.rst +++ b/Doc/library/stringio.rst @@ -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' diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst index dfd21a2..5ac32df 100644 --- a/Doc/library/subprocess.rst +++ b/Doc/library/subprocess.rst @@ -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\* diff --git a/Doc/library/tarfile.rst b/Doc/library/tarfile.rst index dcd62a0..4aabd81 100644 --- a/Doc/library/tarfile.rst +++ b/Doc/library/tarfile.rst @@ -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:: diff --git a/Doc/library/telnetlib.rst b/Doc/library/telnetlib.rst index c1f1260..5cfca9a 100644 --- a/Doc/library/telnetlib.rst +++ b/Doc/library/telnetlib.rst @@ -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()) diff --git a/Doc/library/test.rst b/Doc/library/test.rst index 305c26f..1ba4810 100644 --- a/Doc/library/test.rst +++ b/Doc/library/test.rst @@ -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" diff --git a/Doc/library/textwrap.rst b/Doc/library/textwrap.rst index e4340fa..350354c 100644 --- a/Doc/library/textwrap.rst +++ b/Doc/library/textwrap.rst @@ -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(...) diff --git a/Doc/library/thread.rst b/Doc/library/thread.rst index a2eeb8a..32437dc 100644 --- a/Doc/library/thread.rst +++ b/Doc/library/thread.rst @@ -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:** diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst index a676a1e..828d42b 100644 --- a/Doc/library/threading.rst +++ b/Doc/library/threading.rst @@ -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") diff --git a/Doc/library/timeit.rst b/Doc/library/timeit.rst index bc9615a..3387c7f 100644 --- a/Doc/library/timeit.rst +++ b/Doc/library/timeit.rst @@ -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()) diff --git a/Doc/library/tix.rst b/Doc/library/tix.rst index c7034ed..abe3ca5 100644 --- a/Doc/library/tix.rst +++ b/Doc/library/tix.rst @@ -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) diff --git a/Doc/library/tkinter.rst b/Doc/library/tkinter.rst index c4df617..f6c5c61 100644 --- a/Doc/library/tkinter.rst +++ b/Doc/library/tkinter.rst @@ -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 diff --git a/Doc/library/traceback.rst b/Doc/library/traceback.rst index a9b15db..9b96743 100644 --- a/Doc/library/traceback.rst +++ b/Doc/library/traceback.rst @@ -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) diff --git a/Doc/library/urllib.rst b/Doc/library/urllib.rst index 914351a..3d28c45 100644 --- a/Doc/library/urllib.rst +++ b/Doc/library/urllib.rst @@ -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:: diff --git a/Doc/library/urllib2.rst b/Doc/library/urllib2.rst index 6360ab8..b3e5485 100644 --- a/Doc/library/urllib2.rst +++ b/Doc/library/urllib2.rst @@ -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:: diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst index 44f8d96..940e064 100644 --- a/Doc/library/weakref.rst +++ b/Doc/library/weakref.rst @@ -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 diff --git a/Doc/library/wsgiref.rst b/Doc/library/wsgiref.rst index b3a3a9f..cf1fc97 100644 --- a/Doc/library/wsgiref.rst +++ b/Doc/library/wsgiref.rst @@ -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() diff --git a/Doc/library/xdrlib.rst b/Doc/library/xdrlib.rst index 6339a7f..e9d9367 100644 --- a/Doc/library/xdrlib.rst +++ b/Doc/library/xdrlib.rst @@ -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) diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst index 0ad3b17..5143320 100644 --- a/Doc/library/xml.etree.elementtree.rst +++ b/Doc/library/xml.etree.elementtree.rst @@ -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: diff --git a/Doc/library/xml.sax.utils.rst b/Doc/library/xml.sax.utils.rst index 639b63f..cd16348 100644 --- a/Doc/library/xml.sax.utils.rst +++ b/Doc/library/xml.sax.utils.rst @@ -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 " ef"> This function is useful when generating attribute values for HTML or any SGML diff --git a/Doc/library/xmlrpclib.rst b/Doc/library/xmlrpclib.rst index d2ed771..3b4dbbd 100644 --- a/Doc/library/xmlrpclib.rst +++ b/Doc/library/xmlrpclib.rst @@ -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()) |