Commits

Joey Smith committed e1ec5a4

First phase of converting paster to py3 - most of the changes here were advised by 2to3

Comments (0)

Files changed (62)

paste/auth/auth_tkt.py

     from hashlib import md5
 except ImportError:
     from md5 import md5
-import Cookie
+import http.cookies
 from paste import request
-from urllib import quote as url_quote
-from urllib import unquote as url_unquote
+from urllib.parse import quote as url_quote
+from urllib.parse import unquote as url_unquote
 
 
 class AuthTicket(object):
     digest = ticket[:32]
     try:
         timestamp = int(ticket[32:40], 16)
-    except ValueError, e:
+    except ValueError as e:
         raise BadTicket('Timestamp is not a hex integer: %s' % e)
     try:
         userid, data = ticket[40:].split('!', 1)
 
 
 def encode_ip_timestamp(ip, timestamp):
-    ip_chars = ''.join(map(chr, map(int, ip.split('.'))))
+    ip_chars = ''.join(map(chr, list(map(int, ip.split('.')))))
     t = int(timestamp)
     ts = ((t & 0xff000000) >> 24,
           (t & 0xff0000) >> 16,
 
 
 def maybe_encode(s, encoding='utf8'):
-    if isinstance(s, unicode):
+    if isinstance(s, str):
         s = s.encode(encoding)
     return s
 
         return self.app(environ, cookie_setting_start_response)
 
     def set_user_cookie(self, environ, userid, tokens, user_data):
-        if not isinstance(tokens, basestring):
+        if not isinstance(tokens, str):
             tokens = ','.join(tokens)
         if self.include_ip:
             remote_addr = environ['REMOTE_ADDR']

paste/auth/cas.py

 of processing.  It has the secondary goal of allowing for other
 authentication methods to be used concurrently.
 """
-import urllib
+import urllib.request, urllib.parse, urllib.error
 from paste.request import construct_url
 from paste.httpexceptions import HTTPSeeOther, HTTPForbidden
 
             ticket = qs.pop().split("=", 1)[1]
             environ['QUERY_STRING'] = "&".join(qs)
             service = construct_url(environ)
-            args = urllib.urlencode(
+            args = urllib.parse.urlencode(
                     {'service': service,'ticket': ticket})
             requrl = authority + "validate?" + args
-            result = urllib.urlopen(requrl).read().split("\n")
+            result = urllib.request.urlopen(requrl).read().split("\n")
             if 'yes' == result[0]:
                 environ['REMOTE_USER'] = result[1]
                 environ['AUTH_TYPE'] = 'cas'
             exce = CASLoginFailure()
         else:
             service = construct_url(environ)
-            args = urllib.urlencode({'service': service})
+            args = urllib.parse.urlencode({'service': service})
             location = authority + "login?" + args
             exce = CASAuthenticate(location)
         return exce.wsgi_application(environ, start_response)

paste/auth/cookie.py

 """
 
 import hmac, base64, random, time, warnings
+from functools import reduce
 try:
     from hashlib import sha1
 except ImportError:
     """
     def __init__(self, secret = None, timeout = None, maxlen = None):
         self.timeout = timeout or 30
-        if isinstance(timeout, basestring):
+        if isinstance(timeout, str):
             raise ValueError(
                 "Timeout must be a number (minutes), not a string (%r)"
                 % timeout)
             raise AssertionError("AuthCookie already installed!")
         scanlist = self.environ_class(self, self.scanlist)
         jar = get_cookies(environ)
-        if jar.has_key(self.cookie_name):
+        if self.cookie_name in jar:
             content = self.signer.auth(jar[self.cookie_name].value)
             if content:
                 for pair in content.split(";"):
             which is a typical browser maximum)
         
     """
-    if isinstance(scanlist, basestring):
+    if isinstance(scanlist, str):
         scanlist = scanlist.split()
     if secret is None and global_conf.get('secret'):
         secret = global_conf['secret']

paste/auth/digest.py

 except ImportError:
     from md5 import md5
 import time, random
-from urllib import quote as url_quote
+from urllib.parse import quote as url_quote
 
 def digest_password(realm, username, password):
     """ construct the appropriate hashcode needed for HTTP digest """

paste/auth/grantip.py

         self.clobber_username = clobber_username
 
     def _convert_user_role(self, username, roles):
-        if roles and isinstance(roles, basestring):
+        if roles and isinstance(roles, str):
             roles = roles.split(',')
         return (username, roles)
         
     def _set_roles(self, environ, roles):
         cur_roles = environ.get('REMOTE_USER_TOKENS', '').split(',')
         # Get rid of empty roles:
-        cur_roles = filter(None, cur_roles)
+        cur_roles = [_f for _f in cur_roles if _f]
         remove_roles = []
         for role in roles:
             if role.startswith('-'):

paste/auth/open_id.py

 __all__ = ['AuthOpenIDHandler']
 
 import cgi
-import urlparse
+import urllib.parse
 import re
 
 import paste.request
                                                               with_query_string=False)
 
             path = re.sub(self.auth_prefix, '', environ['PATH_INFO'])
-            request['parsed_uri'] = urlparse.urlparse(path)
+            request['parsed_uri'] = urllib.parse.urlparse(path)
             request['query'] = dict(paste.request.parse_querystring(environ))
 
             path = request['parsed_uri'][2]
     from paste.deploy.converters import asbool
     from paste.util import import_string
     catch_401 = asbool(catch_401)
-    if url_to_username and isinstance(url_to_username, basestring):
+    if url_to_username and isinstance(url_to_username, str):
         url_to_username = import_string.eval_import(url_to_username)
     apply_auth_tkt = asbool(apply_auth_tkt)
     new_app = AuthOpenIDHandler(
 from paste import httpexceptions
 from paste.util import converters
 import tempfile
-from cStringIO import StringIO
+from io import StringIO
 
 __all__ = ['Cascade']
 
         ...
         catch = 404 500 ...
     """
-    catch = map(int, converters.aslist(catch))
+    catch = list(map(int, converters.aslist(catch)))
     apps = []
     for name, value in local_conf.items():
         if not name.startswith('app'):
                         list(v)
                         # then close:
                         v.close()
-            except self.catch_exceptions, e:
+            except self.catch_exceptions as e:
                 pass
         if copy_wsgi_input:
             environ['wsgi.input'].seek(0)
 import os
 import sys
 import subprocess
-import urllib
+import urllib.request, urllib.parse, urllib.error
 try:
     import select
 except ImportError:
     def __call__(self, environ, start_response):
         if 'REQUEST_URI' not in environ:
             environ['REQUEST_URI'] = (
-                urllib.quote(environ.get('SCRIPT_NAME', ''))
-                + urllib.quote(environ.get('PATH_INFO', '')))
+                urllib.parse.quote(environ.get('SCRIPT_NAME', ''))
+                + urllib.parse.quote(environ.get('PATH_INFO', '')))
         if self.include_os_environ:
             cgi_environ = os.environ.copy()
         else:
 
     try:
         proc.wait()
-    except OSError, e:
+    except OSError as e:
         if e.errno != 10:
             raise
 

paste/cgitb_catcher.py

 """
 
 import cgitb
-from cStringIO import StringIO
+from io import StringIO
 import sys
 
 from paste.util import converters
             global_conf = {}
         if display is NoDefault:
             display = global_conf.get('debug')
-        if isinstance(display, basestring):
+        if isinstance(display, str):
             display = converters.asbool(display)
         self.display = display
         self.logdir = logdir

paste/debug/debugapp.py

             remaining = int(total)
             while remaining > 0:
                 if self.progress:
-                    print "%s of %s remaining" % (remaining, total)
+                    print("%s of %s remaining" % (remaining, total))
                 if remaining > 4096:
                     chunk = environ['wsgi.input'].read(4096)
                 else:
                 '<input type="file" name="file">\n'
                 '<input type="submit" >\n'
                 '</form></body></html>\n')
-        print "bingles"
+        print("bingles")
         start_response("200 OK", [('Content-Type', 'text/html'),
                                   ('Content-Length', len(body))])
         return [body]

paste/debug/doctest_webapp.py

 import re
 import cgi
 import rfc822
-from cStringIO import StringIO
+from io import StringIO
 from paste.util import PySourceColor
 
 
 def run(command):
     data = run_raw(command)
     if data:
-        print data
+        print(data)
 
 def run_raw(command):
     """
     show_file('shell-command', name, description='shell transcript',
               data=data)
     if and_print and output:
-        print output
+        print(output)
 
 def _make_env():
     env = os.environ.copy()
         full = os.path.join(dir, fn)
         if os.path.isdir(full):
             fn = fn + '/'
-        print ' '*indent + fn
+        print(' '*indent + fn)
         if os.path.isdir(full) and recurse:
             ls(dir=full, recurse=True, indent=indent+2)
 
         expected = f.read()
         f.close()
         if not html_matches(expected, result):
-            print 'Pages did not match.  Expected from %s:' % fn
-            print '-'*60
-            print expected
-            print '='*60
-            print 'Actual output:'
-            print '-'*60
-            print result
+            print('Pages did not match.  Expected from %s:' % fn)
+            print('-'*60)
+            print(expected)
+            print('='*60)
+            print('Actual output:')
+            print('-'*60)
+            print(result)
 
 def html_matches(pattern, text):
     regex = re.escape(pattern)

paste/debug/fsdiff.py

             ('updated', self.updated, True)]:
             if files:
                 s.append('-- %s: -------------------' % name)
-                files = files.items()
+                files = list(files.items())
                 files.sort()
                 last = ''
                 for path, f in files:
         __tracebackhide__ = True
         bytes = self.bytes
         if s not in bytes:
-            print 'Could not find %r in:' % s
-            print bytes
+            print('Could not find %r in:' % s)
+            print(bytes)
             assert s in bytes
 
     def __repr__(self):
     """
     if not diffs:
         return 'No differences'
-    diffs = diffs.items()
+    diffs = list(diffs.items())
     diffs.sort()
     s = []
     last = ''

paste/debug/prints.py

 
 """
 
-from cStringIO import StringIO
+from io import StringIO
 import re
 import cgi
 from paste.util import threadedprint
         self.files = files
 
     def write(self, v):
-        if isinstance(v, unicode):
+        if isinstance(v, str):
             # WSGI is picky in this case
             v = str(v)
         for file in self.files:
         # the entry point
         self.app = app
         self.force_content_type = force_content_type
-        if isinstance(print_wsgi_errors, basestring):
+        if isinstance(print_wsgi_errors, str):
             from paste.deploy.converters import asbool
             print_wsgi_errors = asbool(print_wsgi_errors)
         self.print_wsgi_errors = print_wsgi_errors

paste/debug/profile.py

 import threading
 import cgi
 import time
-from cStringIO import StringIO
+from io import StringIO
 from paste import response
 
 __all__ = ['ProfileMiddleware', 'profile_decorator']
             f.close()
         if exc_info:
             # We captured an exception earlier, now we re-raise it
-            raise exc_info[0], exc_info[1], exc_info[2]
+            raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
         return result
         
     def format_function(self, func, *args, **kw):
-        args = map(repr, args)
+        args = list(map(repr, args))
         args.extend(
             ['%s=%r' % (k, v) for k, v in kw.items()])
         return '%s(%s)' % (func.__name__, ', '.join(args))

paste/debug/testserver.py

             if now > self.expires and self.timeout:
                 # note regression test doesn't handle exceptions in
                 # threads very well; so we just print and exit
-                print "\nWARNING: WSGIRegressionServer timeout exceeded\n"
+                print("\nWARNING: WSGIRegressionServer timeout exceeded\n")
                 break
             if self.pending:
                 self.handle_request()
 
 def serve(application, host=None, port=None, handler=None):
     server = WSGIRegressionServer(application, host, port, handler)
-    print "serving on %s:%s" % server.server_address
+    print("serving on %s:%s" % server.server_address)
     server.serve_forever()
     return server
 
 if __name__ == '__main__':
-    import urllib
+    import urllib.request, urllib.parse, urllib.error
     from paste.wsgilib import dump_environ
     server = serve(dump_environ)
     baseuri = ("http://%s:%s" % server.server_address)
         import socket
         socket.setdefaulttimeout(5)
         # build a uri, fetch and return
-        return urllib.urlopen(baseuri + path).read()
+        return urllib.request.urlopen(baseuri + path).read()
       
     assert "PATH_INFO: /foo" in fetch("/foo")
     assert "PATH_INFO: /womble" in fetch("/womble")
     # and then schedule a stop()
     server.stop()
     # and then... fetch it...
-    urllib.urlopen(baseuri)
+    urllib.request.urlopen(baseuri)

paste/debug/watchthreads.py

 import cgi
 import time
 import traceback
-from cStringIO import StringIO
-from thread import get_ident
+from io import StringIO
+from _thread import get_ident
 from paste import httpexceptions
 from paste.request import construct_url, parse_formvars
 from paste.util.template import HTMLTemplate, bunch
         now = time.time()
 
 
-        workers = thread_pool.worker_tracker.items()
-        workers.sort(key=lambda v: v[1][0])
+        workers = sorted(thread_pool.worker_tracker.items(), key=lambda v: v[1][0])
         threads = []
         for thread_id, (time_started, worker_environ) in workers:
             thread = bunch()
                 environ_template.substitute(
                 key=cgi.escape(str(key)),
                 value=cgi.escape(str(value))))
-        except Exception, e:
+        except Exception as e:
             environ_rows.append(
                 environ_template.substitute(
                 key=cgi.escape(str(key)),
 def make_bad_app(global_conf, pause=0):
     pause = int(pause)
     def bad_app(environ, start_response):
-        import thread
+        import _thread
         if pause:
             time.sleep(pause)
         else:
             count = 0
             while 1:
-                print "I'm alive %s (%s)" % (count, thread.get_ident())
+                print("I'm alive %s (%s)" % (count, thread.get_ident()))
                 time.sleep(10)
                 count += 1
         start_response('200 OK', [('content-type', 'text/plain')])

paste/debug/wdg_validate.py

 `WDG HTML Validator <http://www.htmlhelp.com/tools/validator/>`_
 """
 
-from cStringIO import StringIO
+from io import StringIO
 try:
     import subprocess
 except ImportError:

paste/errordocument.py

 
 import warnings
 import sys
-from urlparse import urlparse
+from urllib.parse import urlparse
 from paste.recursive import ForwardRequestException, RecursiveMiddleware, RecursionLoop
 from paste.util import converters
 from paste.response import replace_header
                 '%s is not valid'%repr(code))
 
     def error_codes_mapper(code, message, environ, global_conf, codes):
-        if codes.has_key(code):
+        if code in codes:
             return codes[code]
         else:
             return None
         #raise Exception(self.url, self.status)
         try:
             return self.app(environ, keep_status_start_response)
-        except RecursionLoop, e:
+        except RecursionLoop as e:
             environ['wsgi.errors'].write('Recursion error getting error page: %s\n' % e)
             keep_status_start_response('500 Server Error', [('Content-type', 'text/plain')], sys.exc_info())
             return ['Error: %s.  (Error page could not be fetched)'
                 forward.start_response = eat_start_response
                 try:
                     app_iter = forward(url_, new_environ)
-                except InvalidForward, e:
+                except InvalidForward as e:
                     code, message = code_message[0]
                     environ['wsgi.errors'].write(
                         'Error occurred in '

paste/evalexception/evalcontext.py

 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
-from cStringIO import StringIO
+from io import StringIO
 import traceback
 import threading
 import pdb
             sys.stdout = out
             try:
                 code = compile(s, '<web>', "single", 0, 1)
-                exec code in self.namespace, self.globs
+                exec(code, self.namespace, self.globs)
                 debugger.set_continue()
             except KeyboardInterrupt:
                 raise

paste/evalexception/middleware.py

 import os
 import cgi
 import traceback
-from cStringIO import StringIO
+from io import StringIO
 import pprint
 import itertools
 import time
 from paste import registry
 from paste import request
 from paste import response
-import evalcontext
+from . import evalcontext
 
 limit = 200
 
                     % debugcount)
             debug_info = self.debug_infos[debugcount]
             return func(self, debug_info=debug_info, **form)
-        except ValueError, e:
+        except ValueError as e:
             form['headers']['status'] = '500 Server Error'
             return '<html>There was an error: %s</html>' % html_quote(e)
     return debug_info_replacement
     if 'paste.evalexception.debug_count' in environ:
         return environ['paste.evalexception.debug_count']
     else:
-        environ['paste.evalexception.debug_count'] = next = debug_counter.next()
+        environ['paste.evalexception.debug_count'] = next = next(debug_counter)
         return next
 
 class EvalException(object):
             if id(frame) == tbid:
                 return frame
         else:
-            raise ValueError, (
+            raise ValueError(
                 "No frame by id %s found from %r" % (tbid, self.frames))
 
     def wsgi_application(self, environ, start_response):
         out = StringIO()
         try:
             pprint.pprint(value, out)
-        except Exception, e:
+        except Exception as e:
             print >> out, 'Error: %s' % e
         value = html_quote(out.getvalue())
         if len(value) > 100:

paste/exceptions/collector.py

 import sys
 import traceback
 import time
-try:
-    from cStringIO import StringIO
-except ImportError:
-    from StringIO import StringIO
+from io import StringIO
 import linecache
 from paste.exceptions import serial_number_generator
 import warnings
         data['tbid'] = id(tb)
 
         # Output a traceback supplement, if any.
-        if locals.has_key('__traceback_supplement__'):
+        if '__traceback_supplement__' in locals:
             # Use the supplement defined in the function.
             tbs = locals['__traceback_supplement__']
-        elif globals.has_key('__traceback_supplement__'):
+        elif '__traceback_supplement__' in globals:
             # Use the supplement defined in the module.
             # This is used by Scripts (Python).
             tbs = globals['__traceback_supplement__']
             return str(obj)
         except UnicodeEncodeError:
             try:
-                return unicode(obj).encode(FALLBACK_ENCODING, 'replace')
+                return str(obj).encode(FALLBACK_ENCODING, 'replace')
             except UnicodeEncodeError:
                 # This is when something is really messed up, but this can
                 # happen when the __str__ of an object has to handle unicode

paste/exceptions/errormiddleware.py

 import sys
 import traceback
 import cgi
-try:
-    from cStringIO import StringIO
-except ImportError:
-    from StringIO import StringIO
+from io import StringIO
 from paste.exceptions import formatter, collector, reporter
 from paste import wsgilib
 from paste import request
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         __traceback_supplement__ = (
             Supplement, self.error_middleware, self.environ)
         if self.closed:
             raise StopIteration
         try:
-            return self.app_iterator.next()
+            return next(self.app_iterator)
         except StopIteration:
             self.closed = True
             close_response = self._close()

paste/exceptions/formatter.py

                 lines.append(self.format_long_source(
                     source, long_source))
         etype = exc_data.exception_type
-        if not isinstance(etype, basestring):
+        if not isinstance(etype, str):
             etype = etype.__name__
         exc_info = self.format_exception_info(
             etype,
             for n, v in items:
                 try:
                     v = repr(v)
-                except Exception, e:
+                except Exception as e:
                     v = 'Cannot display: %s' % e
                 v = truncate(v)
                 lines.append('  %s: %s' % (n, v))
         for name, value in rows:
             try:
                 value = repr(value)
-            except Exception, e:
+            except Exception as e:
                 value = 'Cannot print: %s' % e
             odd = not odd
             table.append(

paste/exceptions/reporter.py

             raise ValueError("You must set to_addresses")
         if not self.from_address:
             raise ValueError("You must set from_address")
-        if isinstance(self.to_addresses, (str, unicode)):
+        if isinstance(self.to_addresses, str):
             self.to_addresses = [self.to_addresses]
 
     def assemble_email(self, exc_data):

paste/exceptions/serial_number_generator.py

 (or concatenation of strings)
 """
 
-try:
-    from hashlib import md5
-except ImportError:
-    from md5 import md5
+import collections
+from hashlib import md5
 
 good_characters = "23456789abcdefghjkmnpqrtuvwxyz"
 
     """
     Encodes a number as an identifier.
     """
-    if not isinstance(number, (int, long)):
+    if not isinstance(number, int):
         raise ValueError(
             "You can only make identifiers out of integers (not %r)"
             % number)
     length.  E.g., ``group=4`` will cause a identifier like
     ``a5f3-hgk3-asdf``.  Grouping occurs before the prefix.
     """
-    if not callable(hasher):
+    if not isinstance(hasher, collections.Callable):
         # Accept sha/md5 modules as well as callables
         hasher = hasher.new
     if length > 26 and hasher is md5:
-        raise ValueError, (
+        raise ValueError(
             "md5 cannot create hashes longer than 26 characters in "
             "length (you gave %s)" % length)
-    if isinstance(s, unicode):
+    if isinstance(s, str):
         s = s.encode('utf-8')
     h = hasher(str(s))
     bin_hash = h.digest()
                             head.delete(headers)
                         start_response('304 Not Modified', headers)
                         return ['']
-        except HTTPBadRequest, exce:
+        except HTTPBadRequest as exce:
             return exce.wsgi_application(environ, start_response)
 
         # If we get If-None-Match and If-Modified-Since, and
                         head.delete(headers)
                     start_response('304 Not Modified', headers)
                     return [''] # empty body
-            except HTTPBadRequest, exce:
+            except HTTPBadRequest as exce:
                 return exce.wsgi_application(environ, start_response)
 
         (lower, upper) = (0, self.content_length - 1)
                 return exc(environ, start_response)
             try:
                 file = open(self.filename, 'rb')
-            except (IOError, OSError), e:
+            except (IOError, OSError) as e:
                 exc = HTTPForbidden(
                     'You are not permitted to view this file (%s)' % e)
                 return exc.wsgi_application(
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         chunk_size = self.block_size
         if self.size is not None:
             if chunk_size > self.size:
 
 import sys
 import random
-import urllib
-import urlparse
+import urllib.request, urllib.parse, urllib.error
 import mimetypes
 import time
 import cgi
 import shutil
 import smtplib
 import shlex
-from Cookie import BaseCookie
+from http.cookies import BaseCookie
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 import re
 try:
     import subprocess
         ``post_request_hook`` is a function, similar to
         ``pre_request_hook``, to be called after requests are made.
         """
-        if isinstance(app, (str, unicode)):
+        if isinstance(app, str):
             from paste.deploy import loadapp
             # @@: Should pick up relative_to from calling module's
             # __file__
         # Hide from py.test:
         __tracebackhide__ = True
         if params:
-            if not isinstance(params, (str, unicode)):
-                params = urllib.urlencode(params, doseq=True)
+            if not isinstance(params, str):
+                params = urllib.parse.urlencode(params, doseq=True)
             if '?' in url:
                 url += '&'
             else:
         environ = self._make_environ()
         # @@: Should this be all non-strings?
         if isinstance(params, (list, tuple, dict)):
-            params = urllib.urlencode(params)
+            params = urllib.parse.urlencode(params)
         if hasattr(params, 'items'):
             # Some other multi-dict like format
-            params = urllib.urlencode(params.items())
+            params = urllib.parse.urlencode(list(params.items()))
         if upload_files:
             params = cgi.parse_qsl(params, keep_blank_values=True)
             content_type, params = self.encode_multipart(
             raise AppError(
                 "Application had errors logged:\n%s" % res.errors)
 
-    def _make_response(self, (status, headers, body, errors), total_time):
+    def _make_response(self, payload, total_time):
+        (status, headers, body, errors) = payload
         return TestResponse(self, status, headers, body, errors,
                             total_time)
 
             "You can only follow redirect responses (not %s)"
             % self.full_status)
         location = self.header('location')
-        type, rest = urllib.splittype(location)
-        host, path = urllib.splithost(rest)
+        type, rest = urllib.parse.splittype(location)
+        host, path = urllib.parse.splithost(rest)
         # @@: We should test that it's not a remote redirect
         return self.test_app.get(location, **kw)
 
 
         All hostnames and schemes will be ignored.
         """
-        scheme, host, path, query, fragment = urlparse.urlsplit(href)
+        scheme, host, path, query, fragment = urllib.parse.urlsplit(href)
         # We
         scheme = host = fragment = ''
-        href = urlparse.urlunsplit((scheme, host, path, query, fragment))
-        href = urlparse.urljoin(self.request.full_url, href)
+        href = urllib.parse.urlunsplit((scheme, host, path, query, fragment))
+        href = urllib.parse.urljoin(self.request.full_url, href)
         method = method.lower()
         assert method in ('get', 'post'), (
             'Only "get" or "post" are allowed for method (you gave %r)'
         of the response.  Whitespace is normalized when searching
         for a string.
         """
-        if not isinstance(s, (str, unicode)):
+        if not isinstance(s, str):
             s = str(s)
-        if isinstance(s, unicode):
+        if isinstance(s, str):
             ## FIXME: we don't know that this response uses utf8:
             s = s.encode('utf8')
         return (self.body.find(s) != -1
         if 'no' in kw:
             no = kw['no']
             del kw['no']
-            if isinstance(no, basestring):
+            if isinstance(no, str):
                 no = [no]
         else:
             no = []
         cwd = _popget(kw, 'cwd', self.cwd)
         stdin = _popget(kw, 'stdin', None)
         printresult = _popget(kw, 'printresult', True)
-        args = map(str, args)
+        args = list(map(str, args))
         assert not kw, (
             "Arguments not expected: %s" % ', '.join(kw.keys()))
         if ' ' in script:
             ('updated', self.files_updated, True)]:
             if files:
                 s.append('-- %s: -------------------' % name)
-                files = files.items()
-                files.sort()
+                files = sorted(files.items())
                 last = ''
                 for path, f in files:
                     t = '  %s' % _space_prefix(last, path, indent=4,
 def _make_pattern(pat):
     if pat is None:
         return None
-    if isinstance(pat, (str, unicode)):
+    if isinstance(pat, str):
         pat = re.compile(pat)
     if hasattr(pat, 'search'):
         return pat.search
-    if callable(pat):
+    if isinstance(pat, collections.Callable):
         return pat
     assert 0, (
         "Cannot make callable pattern object out of %r" % pat)
     if module is None:
         # The module we were called from must be the module...
         module = sys._getframe().f_back.f_globals['__name__']
-    if isinstance(module, (str, unicode)):
+    if isinstance(module, str):
         module = sys.modules[module]
     if hasattr(module, 'reset_state'):
         module.reset_state()

paste/flup_session.py

 
         try:
             app_iter = self.application(environ, cookie_start_response)
-        except httpexceptions.HTTPException, e:
+        except httpexceptions.HTTPException as e:
             headers = (e.headers or {}).items()
             service.addCookie(headers)
             e.headers = dict(headers)
 import gzip
 from paste.response import header_value, remove_header
 from paste.httpheaders import CONTENT_LENGTH
-
-try:
-    from cStringIO import StringIO
-except ImportError:
-    from StringIO import StringIO
+from io import StringIO
 
 class GzipOutput(object):
     pass

paste/httpexceptions.py

         assert isinstance(headers, (type(None), list)), (
             "headers must be None or a list: %r"
             % headers)
-        assert isinstance(detail, (type(None), basestring)), (
+        assert isinstance(detail, (type(None), str)), (
             "detail must be None or a string: %r" % detail)
-        assert isinstance(comment, (type(None), basestring)), (
+        assert isinstance(comment, (type(None), str)), (
             "comment must be None or a string: %r" % comment)
         self.headers = headers or tuple()
         for req in self.required_headers:
                 for (k, v) in self.headers:
                     args[k.lower()] = escfunc(v)
         for key, value in args.items():
-            if isinstance(value, unicode):
+            if isinstance(value, str):
                 args[key] = value.encode('utf8', 'xmlcharrefreplace')
         return template % args
 
         else:
             replace_header(headers, 'content-type', 'text/plain')
             content = self.plain(environ)
-        if isinstance(content, unicode):
+        if isinstance(content, str):
             content = content.encode('utf8')
             cur_content_type = (
                 header_value(headers, 'content-type')
 
 _exceptions = {}
 for name, value in globals().items():
-    if (isinstance(value, (type, types.ClassType)) and
+    if (isinstance(value, type) and
         issubclass(value, HTTPException) and
         value.code):
         _exceptions[value.code] = value
                            []).append(HTTPException)
         try:
             return self.application(environ, start_response)
-        except HTTPException, exc:
+        except HTTPException as exc:
             return exc(environ, start_response)
 
 def middleware(*args, **kw):

paste/httpheaders.py

 
 """
 import mimetypes
-import urllib2
+import urllib.request, urllib.error, urllib.parse
 import re
 from rfc822 import formatdate, parsedate_tz, mktime_tz
 from time import time as now
-from httpexceptions import HTTPBadRequest
+from .httpexceptions import HTTPBadRequest
 
 __all__ = ['get_header', 'list_headers', 'normalize_headers',
            'HTTPHeader', 'EnvironVariable' ]

paste/httpserver.py

 
 import atexit
 import traceback
-import socket, sys, threading, urlparse, Queue, urllib
+import socket, sys, threading, urllib.parse, queue, urllib.request, urllib.parse, urllib.error
 import posixpath
 import time
-import thread
+import _thread
 import os
 from itertools import count
-from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
-from SocketServer import ThreadingMixIn
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from socketserver import ThreadingMixIn
 from paste.util import converters
 import logging
 try:
         if exc_info:
             try:
                 if self.wsgi_headers_sent:
-                    raise exc_info[0], exc_info[1], exc_info[2]
+                    raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
                 else:
                     # In this case, we're going to assume that the
                     # higher-level code is currently handling the
         argument can be used to override any settings.
         """
 
-        (scheme, netloc, path, query, fragment) = urlparse.urlsplit(self.path)
-        path = urllib.unquote(path)
+        (scheme, netloc, path, query, fragment) = urllib.parse.urlsplit(self.path)
+        path = urllib.parse.unquote(path)
         endslash = path.endswith('/')
         path = posixpath.normpath(path)
         if endslash and path != '/':
                 if hasattr(result,'close'):
                     result.close()
                 result = None
-        except socket.error, exce:
+        except socket.error as exce:
             self.wsgi_connection_drop(exce, environ)
             return
         except:
 
         cert = OpenSSL.crypto.X509()
 
-        cert.set_serial_number(random.randint(0, sys.maxint))
+        cert.set_serial_number(random.randint(0, sys.maxsize))
         cert.gmtime_adj_notBefore(0)
         cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)
         cert.get_subject().CN = '*'
         # don't bother logging disconnects while handling a request
         try:
             BaseHTTPRequestHandler.handle(self)
-        except SocketErrors, exce:
+        except SocketErrors as exce:
             self.wsgi_connection_drop(exce)
 
     def address_string(self):
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         if self.length - self._consumed <= 0:
             raise StopIteration
         return self.readline()
         self.nworkers = nworkers
         self.max_requests = max_requests
         self.name = name
-        self.queue = Queue.Queue()
+        self.queue = queue.Queue()
         self.workers = []
         self.daemon = daemon
         if logger is None:
             logger = logging.getLogger('paste.httpserver.ThreadPool')
-        if isinstance(logger, basestring):
+        if isinstance(logger, str):
             logger = logging.getLogger(logger)
         self.logger = logger
         self.error_email = error_email
         return thread_id in threading._active
 
     def add_worker_thread(self, *args, **kwargs):
-        index = self._worker_count.next()
+        index = next(self._worker_count)
         worker = threading.Thread(target=self.worker_thread_callback,
                                   args=args, kwargs=kwargs,
                                   name=("worker %d" % index))
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         assert not self.closed, (
             "Iterator read after closed")
-        v = self.iterator.next()
+        v = next(self.iterator)
         if self.check_start_response is not None:
             assert self.check_start_response, (
                 "The application returns and we started iterating over its body, but start_response has not yet been called")
             "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
 
     if not environ.get('SCRIPT_NAME'):
-        assert environ.has_key('PATH_INFO'), (
+        assert 'PATH_INFO' in environ, (
             "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
             "should at least be '/' if SCRIPT_NAME is empty)")
     assert environ.get('SCRIPT_NAME') != '/', (

paste/modpython.py

         if exc_info:
             try:
                 if self.started:
-                    raise exc_info[0], exc_info[1], exc_info[2]
+                    raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
             finally:
                 exc_info = None
         
   
 """
 
-import httplib
-import urlparse
-import urllib
+import http.client
+import urllib.request, urllib.parse, urllib.error
 
 from paste import httpexceptions
 from paste.util.converters import aslist
         else:
             body = ''
             
-        path_info = urllib.quote(environ['PATH_INFO'])
+        path_info = urllib.parse.quote(environ['PATH_INFO'])
         if self.path:            
             request_path = path_info
             if request_path and request_path[0] == '/':
         
         path = (environ.get('SCRIPT_NAME', '')
                 + environ.get('PATH_INFO', ''))
-        path = urllib.quote(path)
+        path = urllib.parse.quote(path)
         if 'QUERY_STRING' in environ:
             path += '?' + environ['QUERY_STRING']
         conn.request(environ['REQUEST_METHOD'],

paste/recursive.py

 (aborting the current request).
 """
 
-from cStringIO import StringIO
+from io import StringIO
 import warnings
 
 __all__ = ['RecursiveMiddleware']
         environ['paste.recursive.script_name'] = my_script_name
         try:
             return self.application(environ, start_response)
-        except ForwardRequestException, e:
+        except ForwardRequestException as e:
             middleware = CheckForRecursionMiddleware(
                 e.factory(self), environ)
             return middleware(environ, start_response)
         response = IncludedResponse()
         def start_response(status, headers, exc_info=None):
             if exc_info:
-                raise exc_info[0], exc_info[1], exc_info[2]
+                raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
             response.status = status
             response.headers = headers
             return response.write
         response = IncludedAppIterResponse()
         def start_response(status, headers, exc_info=None):
             if exc_info:
-                raise exc_info[0], exc_info[1], exc_info[2]
+                raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
             response.status = status
             response.headers = headers
             return response.write

paste/registry.py

     def __contains__(self, key):
         return key in self._current_obj()
 
-    def __nonzero__(self):
+    def __bool__(self):
         return bool(self._current_obj())
 
     def _current_obj(self):
     def cleanup(self):
         """Remove all objects from all StackedObjectProxy instances that
         were tracked at this Registry context"""
-        for stacked, obj in self.reglist[-1].itervalues():
+        for stacked, obj in self.reglist[-1].values():
             stacked._pop_object(obj)
         self.reglist.pop()
 
 
         try:
             app_iter = self.application(environ, start_response)
-        except Exception, e:
+        except Exception as e:
             # Regardless of if the content is an iterable, generator, list
             # or tuple, we clean-up right now. If its an iterable/generator
             # care should be used to ensure the generator has its own ref
         try:
             for item in self.application(environ, start_response):
                 yield item
-        except Exception, e:
+        except Exception as e:
             # Regardless of if the content is an iterable, generator, list
             # or tuple, we clean-up right now. If its an iterable/generator
             # care should be used to ensure the generator has its own ref
         # their methods to act differently when a restoration context is active
         # in the current thread
         for reglist in registry.reglist:
-            for stacked, obj in reglist.itervalues():
+            for stacked, obj in reglist.values():
                 self.enable_restoration(stacked)
 
     def get_saved_proxied_obj(self, stacked, request_id):

paste/reloader.py

         for module in sys.modules.values():
             try:
                 filename = module.__file__
-            except (AttributeError, ImportError), exc:
+            except (AttributeError, ImportError) as exc:
                 continue
             if filename is not None:
                 filenames.append(filename)
             elif filename.endswith('$py.class') and \
                     os.path.exists(filename[:-9] + '.py'):
                 mtime = max(os.stat(filename[:-9] + '.py').st_mtime, mtime)
-            if not self.module_mtimes.has_key(filename):
+            if filename not in self.module_mtimes:
                 self.module_mtimes[filename] = mtime
             elif self.module_mtimes[filename] < mtime:
                 print >> sys.stderr, (
 
 """
 import cgi
-from Cookie import SimpleCookie, CookieError
-from StringIO import StringIO
-import urlparse
-import urllib
+from http.cookies import SimpleCookie, CookieError
+from io import StringIO
+import urllib.request, urllib.parse, urllib.error
 try:
     from UserDict import DictMixin
 except ImportError:
 
     """
     header = environ.get('HTTP_COOKIE', '')
-    if environ.has_key('paste.cookies'):
+    if 'paste.cookies' in environ:
         cookies, check_header = environ['paste.cookies']
         if check_header == header:
             return cookies
     header = environ.get('HTTP_COOKIE')
     if not header:
         return {}
-    if environ.has_key('paste.cookies.dict'):
+    if 'paste.cookies.dict' in environ:
         cookies, check_header = environ['paste.cookies.dict']
         if check_header == header:
             return cookies
                 url += ':' + environ['SERVER_PORT']
 
     if script_name is None:
-        url += urllib.quote(environ.get('SCRIPT_NAME',''))
+        url += urllib.parse.quote(environ.get('SCRIPT_NAME',''))
     else:
-        url += urllib.quote(script_name)
+        url += urllib.parse.quote(script_name)
     if with_path_info:
         if path_info is None:
-            url += urllib.quote(environ.get('PATH_INFO',''))
+            url += urllib.parse.quote(environ.get('PATH_INFO',''))
         else:
-            url += urllib.quote(path_info)
+            url += urllib.parse.quote(path_info)
     if with_query_string:
         if querystring is None:
             if environ.get('QUERY_STRING'):
     yield a sequence of those (header_name, value) tuples.
     """
     # @@: Maybe should parse out comma-separated headers?
-    for cgi_var, value in environ.iteritems():
+    for cgi_var, value in environ.items():
         if cgi_var in _parse_headers_special:
             yield _parse_headers_special[cgi_var], value
         elif cgi_var.startswith('HTTP_'):
 expired.
 """
 
-from Cookie import SimpleCookie
+from http.cookies import SimpleCookie
 import time
 import random
 import os
 import datetime
 import threading
 import tempfile
-
-try:
-    import cPickle
-except ImportError:
-    import pickle as cPickle
-try:
-    from hashlib import md5
-except ImportError:
-    from md5 import md5
+import pickle
+from hashlib import md5
 from paste import wsgilib
 from paste import request
 
             return self.session.data()
         cookies = request.get_cookies(self.environ)
         session = None
-        if cookies.has_key(self.cookie_name):
+        if self.cookie_name in cookies:
             self.sid = cookies[self.cookie_name].value
             try:
                 session = self.session_class(self.sid, create=False,
         if self.session is not None:
             return True
         cookies = request.get_cookies(self.environ)
-        if cookies.has_key(self.cookie_name):
+        if self.cookie_name in cookies:
             return True
         return False
 
                  chmod=None,
                  expiration=2880, # in minutes: 48 hours
                  ):
-        if chmod and isinstance(chmod, basestring):
+        if chmod and isinstance(chmod, str):
             chmod = int(chmod, 8)
         self.chmod = chmod
         if not sid:
             return self._data
         if os.path.exists(self.filename()):
             f = open(self.filename(), 'rb')
-            self._data = cPickle.load(f)
+            self._data = pickle.load(f)
             f.close()
         else:
             self._data = {}
                     os.unlink(filename)
             else:
                 f = open(filename, 'wb')
-                cPickle.dump(self._data, f)
+                pickle.dump(self._data, f)
                 f.close()
                 if not exists and self.chmod:
                     os.chmod(filename, self.chmod)

paste/transaction.py

    This is experimental, and will change in the future.
 """
 from paste.httpexceptions import HTTPException
-from wsgilib import catch_errors
+from .wsgilib import catch_errors
 
 class TransactionManagerMiddleware(object):
 

paste/translogger.py

 
 import logging
 import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 class TransLogger(object):
     """
 
     def __call__(self, environ, start_response):
         start = time.localtime()
-        req_uri = urllib.quote(environ.get('SCRIPT_NAME', '')
+        req_uri = req_uri = urllib.parse.quote(environ.get('SCRIPT_NAME', '')
                                + environ.get('PATH_INFO', ''))
         if environ.get('QUERY_STRING'):
             req_uri += '?'+environ['QUERY_STRING']
     setup_console_handler=True,
     set_logger_level=logging.DEBUG):
     from paste.util.converters import asbool
-    if isinstance(logging_level, basestring):
+    if isinstance(logging_level, str):
         logging_level = logging._levelNames[logging_level]
-    if isinstance(set_logger_level, basestring):
+    if isinstance(set_logger_level, str):
         set_logger_level = logging._levelNames[set_logger_level]
     return TransLogger(
         app,
 """
 This module implements a class for handling URLs.
 """
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import cgi
 from paste import request
 # Imported lazily from FormEncode:
 def url_quote(v):
     if v is None:
         return ''
-    return urllib.quote(str(v))
+    return urllib.parse.quote(str(v))
 
-url_unquote = urllib.unquote
+url_unquote = urllib.parse.unquote
 
 def js_repr(v):
     if v is None:
              for key, value in v])
     elif isinstance(v, str):
         return repr(v)
-    elif isinstance(v, unicode):
+    elif isinstance(v, str):
         # @@: how do you do Unicode literals in Javascript?
         return repr(v.encode('UTF-8'))
     elif isinstance(v, (float, int)):
         return repr(v)
-    elif isinstance(v, long):
+    elif isinstance(v, int):
         return repr(v).lstrip('L')
     elif hasattr(v, '__js_repr__'):
         return v.__js_repr__()
                 elif val is None:
                     continue
                 vars.append((name, val))
-            s += urllib.urlencode(vars, True)
+            s += urllib.parse.urlencode(vars, True)
         return s
 
     href = property(href__get)
         self.builder = builder
 
     def __setitem__(self, url, app):
-        if isinstance(app, (str, unicode)):
+        if isinstance(app, str):
             app_fn = os.path.join(self.base_path, app)
             app = self.builder(app_fn)
         url = self.map.normalize_url(url)

paste/urlparser.py

 from paste import fileapp
 from paste.util import import_string
 from paste import httpexceptions
-from httpheaders import ETAG
+from .httpheaders import ETAG
 from paste.util import converters
 
 class NoDefault(object):
                     "'constructor .ext = import_expr'; you gave %r "
                     "(=%r)" % (name, value))
             ext = name[len('constructor '):].strip()
-            if isinstance(value, (str, unicode)):
+            if isinstance(value, str):
                 value = import_string.eval_import(value)
             self.constructors[ext] = value
 
         ``environ`` and ``filename``, and returns a WSGI application.
         """
         d = cls.global_constructors
-        assert not d.has_key(extension), (
+        assert extension not in d, (
             "A constructor already exists for the extension %r (%r) "
             "when attemption to register constructor %r"
             % (extension, d[extension], constructor))
                                  environ['wsgi.errors'])
 
 def load_module_from_name(environ, filename, module_name, errors):
-    if sys.modules.has_key(module_name):
+    if module_name in sys.modules:
         return sys.modules[module_name]
     init_filename = os.path.join(os.path.dirname(filename), '__init__.py')
     if not os.path.exists(init_filename):
         try:
             f = open(init_filename, 'w')
-        except (OSError, IOError), e:
+        except (OSError, IOError) as e:
             errors.write(
                 'Cannot write __init__.py file into directory %s (%s)\n'
                 % (os.path.dirname(filename), e))
         f.write('#\n')
         f.close()
     fp = None
-    if sys.modules.has_key(module_name):
+    if module_name in sys.modules:
         return sys.modules[module_name]
     if '.' in module_name:
         parent_name = '.'.join(module_name.split('.')[:-1])
     def __init__(self, egg_or_spec, resource_name, manager=None, root_resource=None):
         if pkg_resources is None:
             raise NotImplementedError("This class requires pkg_resources.")
-        if isinstance(egg_or_spec, (str, unicode)):
+        if isinstance(egg_or_spec, str):
             self.egg = pkg_resources.get_distribution(egg_or_spec)
         else:
             self.egg = egg_or_spec
         # @@: I don't know what to do with the encoding.
         try:
             file = self.egg.get_resource_stream(self.manager, resource)
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             exc = httpexceptions.HTTPForbidden(
                 'You are not permitted to view this file (%s)' % e)
             return exc.wsgi_application(environ, start_response)

paste/util/classinit.py

 
     def __new__(meta, class_name, bases, new_attrs):
         cls = type.__new__(meta, class_name, bases, new_attrs)
-        if (new_attrs.has_key('__classinit__')
+        if ('__classinit__' in new_attrs
             and not isinstance(cls.__classinit__, staticmethod)):
             setattr(cls, '__classinit__',
-                    staticmethod(cls.__classinit__.im_func))
+                    staticmethod(cls.__classinit__.__func__))
         if hasattr(cls, '__classinit__'):
             cls.__classinit__(cls, new_attrs)
         return cls

paste/util/classinstance.py

         self.type = type
 
     def __call__(self, *args, **kw):
-        assert not kw.has_key('self') and not kw.has_key('cls'), (
+        assert 'self' not in kw and 'cls' not in kw, (
             "You cannot use 'self' or 'cls' arguments to a "
             "classinstancemethod")
         return self.func(*((self.obj, self.type) + args), **kw)
     def __repr__(self):
         if self.obj is None:
             return ('<bound class method %s.%s>'
-                    % (self.type.__name__, self.func.func_name))
+                    % (self.type.__name__, self.func.__name__))
         else:
             return ('<bound method %s.%s of %r>'
-                    % (self.type.__name__, self.func.func_name, self.obj))
+                    % (self.type.__name__, self.func.__name__, self.obj))

paste/util/converters.py

 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 def asbool(obj):
-    if isinstance(obj, (str, unicode)):
+    if isinstance(obj, str):
         obj = obj.strip().lower()
         if obj in ['true', 'yes', 'on', 'y', 't', '1']:
             return True
     return bool(obj)
 
 def aslist(obj, sep=None, strip=True):
-    if isinstance(obj, (str, unicode)):
+    if isinstance(obj, str):
         lst = obj.split(sep)
         if strip:
             lst = [v.strip() for v in lst]

paste/util/dateinterval.py

     'm': minute,
     's': second,
     }
-timeOrdered = timeValues.items()
-timeOrdered.sort(lambda a, b: -cmp(a[1], b[1]))
+timeOrdered = sorted(timeValues.items(), lambda a, b: -cmp(a[1], b[1]))
     
 def interval_encode(seconds, include_sign=False):
     """Encodes a number of seconds (representing a time interval)
         s = s[1:]
     for match in allMatches(s, _timeRE):
         char = match.group(0)[-1].lower()
-        if not timeValues.has_key(char):
+        if char not in timeValues:
             # @@: should signal error
             continue
         time += int(match.group(0)[:-1]) * timeValues[char]

paste/util/doctest24.py

 import sys, traceback, inspect, linecache, os, re, types
 import unittest, difflib, pdb, tempfile
 import warnings
-from StringIO import StringIO
+from io import StringIO
 
 # Don't whine about the deprecated is_private function in this
 # module's tests.
     """
     if inspect.ismodule(module):
         return module
-    elif isinstance(module, (str, unicode)):
+    elif isinstance(module, str):
         return __import__(module, globals(), locals(), ["*"])
     elif module is None:
         return sys.modules[sys._getframe(depth).f_globals['__name__']]
 # [XX] Normalize with respect to os.path.pardir?
 def _module_relative_path(module, path):
     if not inspect.ismodule(module):
-        raise TypeError, 'Expected a module: %r' % module
+        raise TypeError('Expected a module: %r' % module)
     if path.startswith('/'):
-        raise ValueError, 'Module-relative files may not have absolute paths'
+        raise ValueError('Module-relative files may not have absolute paths')
 
     # Find the base directory for the path.
     if hasattr(module, '__file__'):
         Create a new DocTest containing the given examples.  The
         DocTest's globals are initialized with a copy of `globs`.
         """
-        assert not isinstance(examples, basestring), \
+        assert not isinstance(examples, str), \
                "DocTest no longer accepts str; use DocTestParser instead"
         self.examples = examples
         self.docstring = docstring
         if module is None:
             return True
         elif inspect.isfunction(object):
-            return module.__dict__ is object.func_globals
+            return module.__dict__ is object.__globals__
         elif inspect.isclass(object):
             return module.__name__ == object.__module__
         elif inspect.getmodule(object) is not None:
         # Look for tests in a module's __test__ dictionary.
         if inspect.ismodule(obj) and self._recurse:
             for valname, val in getattr(obj, '__test__', {}).items():
-                if not isinstance(valname, basestring):
+                if not isinstance(valname, str):
                     raise ValueError("DocTestFinder.find: __test__ keys "
                                      "must be strings: %r" %
                                      (type(valname),))
                 if not (inspect.isfunction(val) or inspect.isclass(val) or
                         inspect.ismethod(val) or inspect.ismodule(val) or
-                        isinstance(val, basestring)):
+                        isinstance(val, str)):
                     raise ValueError("DocTestFinder.find: __test__ values "
                                      "must be strings, functions, methods, "
                                      "classes, or modules: %r" %
                 if isinstance(val, staticmethod):
                     val = getattr(obj, valname)
                 if isinstance(val, classmethod):
-                    val = getattr(obj, valname).im_func
+                    val = getattr(obj, valname).__func__
 
                 # Recurse to methods, properties, and nested classes.
                 if ((inspect.isfunction(val) or inspect.isclass(val) or
         """
         # Extract the object's docstring.  If it doesn't have one,
         # then return None (no test for this object).
-        if isinstance(obj, basestring):
+        if isinstance(obj, str):
             docstring = obj
         else:
             try:
                     docstring = ''
                 else:
                     docstring = obj.__doc__
-                    if not isinstance(docstring, basestring):
+                    if not isinstance(docstring, str):
                         docstring = str(docstring)
             except (TypeError, AttributeError):
                 docstring = ''
                     break
 
         # Find the line number for functions & methods.
-        if inspect.ismethod(obj): obj = obj.im_func
-        if inspect.isfunction(obj): obj = obj.func_code
+        if inspect.ismethod(obj): obj = obj.__func__
+        if inspect.isfunction(obj): obj = obj.__code__
         if inspect.istraceback(obj): obj = obj.tb_frame
         if inspect.isframe(obj): obj = obj.f_code
         if inspect.iscode(obj):
         # to modify them).
         original_optionflags = self.optionflags
 
-        SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
+        SUCCESS, FAILURE, BOOM = list(range(3)) # `outcome` state
 
         check = self._checker.check_output
 
             # keyboard interrupts.)
             try:
                 # Don't blink!  This is where the user's code gets run.
-                exec compile(example.source, filename, "single",
-                             compileflags, 1) in test.globs
+                exec(compile(example.source, filename, "single",
+                             compileflags, 1) in test.globs)
                 self.debugger.set_continue() # ==== Example Finished ====
                 exception = None
             except KeyboardInterrupt:
 
         if pm:
             try:
-                execfile(srcfilename, globs, globs)
+                exec(compile(open(srcfilename).read(), srcfilename, 'exec'), globs, globs)
             except:
                 print sys.exc_info()[1]
                 pdb.post_mortem(sys.exc_info()[2])

paste/util/filemixin.py

     def flush(self):
         pass
 
-    def next(self):
+    def __next__(self):
         return self.readline()
 
     def readline(self, size=None):

paste/util/findpackage.py

     """
     dir = os.path.abspath(dir)
     orig_dir = dir
-    path = map(os.path.abspath, sys.path)
+    path = list(map(os.path.abspath, sys.path))
     packages = []
     last_dir = None
     while 1:

paste/util/import_string.py

         try:
             module = import_module(name)
             parts = parts[1:]
-        except ImportError, e:
+        except ImportError as e:
             last_import_error = e
             break
     obj = module
     """
     try:
         return import_module(module_name)
-    except ImportError, e:
+    except ImportError as e:
         if not getattr(e, 'args', None):
             raise
         desc = e.args[0]

paste/util/intset.py

         self._neg = neg
 
     def __lt__(self,value):
-        if not isinstance(value,(int,long,_Infinity)):
+        if not isinstance(value,(int,_Infinity)):
             return NotImplemented
         return ( self._neg and
                  not ( isinstance(value,_Infinity) and value._neg ) )
 
     def __le__(self,value):
-        if not isinstance(value,(int,long,_Infinity)):
+        if not isinstance(value,(int,_Infinity)):
             return NotImplemented
         return self._neg
 
     def __gt__(self,value):
-        if not isinstance(value,(int,long,_Infinity)):
+        if not isinstance(value,(int,_Infinity)):
             return NotImplemented
         return not ( self._neg or
                      ( isinstance(value,_Infinity) and not value._neg ) )
 
     def __ge__(self,value):
-        if not isinstance(value,(int,long,_Infinity)):
+        if not isinstance(value,(int,_Infinity)):
             return NotImplemented
         return not self._neg
 
     def __eq__(self,value):
-        if not isinstance(value,(int,long,_Infinity)):
+        if not isinstance(value,(int,_Infinity)):
             return NotImplemented
         return isinstance(value,_Infinity) and self._neg == value._neg
 
     def __ne__(self,value):
-        if not isinstance(value,(int,long,_Infinity)):
+        if not isinstance(value,(int,_Infinity)):
             return NotImplemented
-        return not isinstance(value,_Infinity) or self._neg <> value._neg
+        return not isinstance(value,_Infinity) or self._neg != value._neg
 
     def __repr__(self):
         return "None"
         # Check keyword arguments.
         if kwargs:
             raise ValueError("Invalid keyword argument.")
-        if not ( isinstance(self._min,(int,long)) or self._min is _MININF ):
+        if not ( isinstance(self._min, int) or self._min is _MININF ):
             raise TypeError("Invalid type of min argument.")
-        if not ( isinstance(self._max,(int,long)) or self._max is _MAXINF ):
+        if not ( isinstance(self._max, int) or self._max is _MAXINF ):
             raise TypeError("Invalid type of max argument.")
         if ( self._min is not _MININF and self._max is not _MAXINF and
              self._min > self._max ):
             raise ValueError("Minimum is not smaller than maximum.")
-        if isinstance(self._max,(int,long)):
+        if isinstance(self._max, int):