diff --git a/docs/StyleGuide.txt b/docs/StyleGuide.txt index b3072820..18f97874 100644 --- a/docs/StyleGuide.txt +++ b/docs/StyleGuide.txt @@ -64,7 +64,7 @@ Python Style Guide. Some things to take particular note of: * Docstrings are good. They should look like:: - class AClass(object): + class AClass: """ doc string... """ diff --git a/docs/do-it-yourself-framework.txt b/docs/do-it-yourself-framework.txt index 95b869b9..32d12aae 100644 --- a/docs/do-it-yourself-framework.txt +++ b/docs/do-it-yourself-framework.txt @@ -150,7 +150,7 @@ have to start with some root object, of course, which we'll pass in... :: - class ObjectPublisher(object): + class ObjectPublisher: def __init__(self, root): self.root = root @@ -222,7 +222,7 @@ class into a module ``objectpub``:: from objectpub import ObjectPublisher - class Root(object): + class Root: # The "index" method: def __call__(self): @@ -260,12 +260,12 @@ request is a little slim. # insensitive keys: from paste.response import HeaderDict - class Request(object): + class Request: def __init__(self, environ): self.environ = environ self.fields = parse_formvars(environ) - class Response(object): + class Response: def __init__(self): self.headers = HeaderDict( {'content-type': 'text/html'}) @@ -286,7 +286,7 @@ we'll attach the request and response objects here. So, let's remind ourselves of what the ``__call__`` function looked like:: - class ObjectPublisher(object): + class ObjectPublisher: ... def __call__(self, environ, start_response): @@ -301,7 +301,7 @@ Lets's update that:: import threading webinfo = threading.local() - class ObjectPublisher(object): + class ObjectPublisher: ... def __call__(self, environ, start_response): @@ -361,7 +361,7 @@ response). To give an example of a really really simple middleware, here's one that capitalizes the response:: - class Capitalizer(object): + class Capitalizer: # We generally pass in the application to be wrapped to # the middleware constructor: @@ -391,7 +391,7 @@ is a somewhat more thorough implementation of this. from webob import Request - class Capitalizer(object): + class Capitalizer: def __init__(self, app): self.app = app def __call__(self, environ, start_response): @@ -402,7 +402,7 @@ is a somewhat more thorough implementation of this. So here's some code that does something useful, authentication:: - class AuthMiddleware(object): + class AuthMiddleware: def __init__(self, wrap_app): self.wrap_app = wrap_app @@ -450,7 +450,7 @@ So here's some code that does something useful, authentication:: from webob import Request, Response - class AuthMiddleware(object): + class AuthMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): diff --git a/docs/url-parsing-with-wsgi.txt b/docs/url-parsing-with-wsgi.txt index 856971fa..1b7cb03e 100644 --- a/docs/url-parsing-with-wsgi.txt +++ b/docs/url-parsing-with-wsgi.txt @@ -69,7 +69,7 @@ request and responsibility for the response off to another object (another actor, really). In the process we can actually retain some control -- we can capture and transform the response, and we can modify the request -- but that's not what the typical URL resolver will -do. +do. Motivations =========== @@ -80,7 +80,7 @@ Typically when a framework first supports WSGI or is integrated into Paste, it is "monolithic" with respect to URLs. That is, you define (in Paste, or maybe in Apache) a "root" URL, and everything under that goes into the framework. What the framework does internally, Paste -does not know -- it probably finds internal objects to dispatch to, +does not know -- it probably finds internal objects to dispatch to, but the framework is opaque to Paste. Not just to Paste, but to any code that isn't in that framework. @@ -171,7 +171,7 @@ in turn may delegate to yet another application. Here's a very simple implementation of URLParser:: - class URLParser(object): + class URLParser: def __init__(self, dir): self.dir = dir def __call__(self, environ, start_response): @@ -217,7 +217,7 @@ handle it. This "application" might be a URLParser or similar system :: - class GrabDate(object): + class GrabDate: def __init__(self, subapp): self.subapp = subapp def __call__(self, environ, start_response): @@ -249,12 +249,12 @@ well -- it usually just means use ``getattr`` with the popped segments. But we'll implement a rough approximation of `Quixote's `_ URL parsing:: - class ObjectApp(object): + class ObjectApp: def __init__(self, obj): self.obj = obj def __call__(self, environ, start_response): next = wsgilib.path_info_pop(environ) - if next is None: + if next is None: # This is the object, lets serve it... return self.publish(obj, environ, start_response) next = next or '_q_index' # the default index method @@ -288,7 +288,7 @@ Things to note: (when ``next`` is ``None``). This means ``_q_traverse`` has to consume extra segments of the path. In this version ``_q_traverse`` is only given the next piece of the path; Quixote gives it the - entire path (as a list of segments). + entire path (as a list of segments). * ``publish`` is really a small and lame way to turn a Quixote object into a WSGI application. For any serious framework you'd want to do @@ -298,7 +298,7 @@ Things to note: `_ to convert objects into applications. This would include removing the explicit creation of new ``ObjectApp`` instances, which could also be a kind of fall-back - adaptation. + adaptation. Anyway, this example is less complete, but maybe it will get you thinking. diff --git a/paste/auth/auth_tkt.py b/paste/auth/auth_tkt.py index 4237fed5..17d3478f 100644 --- a/paste/auth/auth_tkt.py +++ b/paste/auth/auth_tkt.py @@ -52,7 +52,7 @@ DEFAULT_DIGEST = hashlib.md5 -class AuthTicket(object): +class AuthTicket: """ This class represents an authentication token. You must pass in @@ -221,7 +221,7 @@ def maybe_encode(s, encoding='utf8'): return s -class AuthTKTMiddleware(object): +class AuthTKTMiddleware: """ Middleware that checks for signed cookies that match what diff --git a/paste/auth/basic.py b/paste/auth/basic.py index c61d26cc..6b1beabf 100644 --- a/paste/auth/basic.py +++ b/paste/auth/basic.py @@ -31,7 +31,7 @@ WWW_AUTHENTICATE, ) -class AuthBasicAuthenticator(object): +class AuthBasicAuthenticator: """ implements ``Basic`` authentication details """ @@ -59,7 +59,7 @@ def authenticate(self, environ): __call__ = authenticate -class AuthBasicHandler(object): +class AuthBasicHandler: """ HTTP/1.0 ``Basic`` authentication middleware diff --git a/paste/auth/cookie.py b/paste/auth/cookie.py index 79b10a5c..2c36c2dc 100644 --- a/paste/auth/cookie.py +++ b/paste/auth/cookie.py @@ -79,7 +79,7 @@ def new_secret(): secret = secret.encode('utf8') return secret -class AuthCookieSigner(object): +class AuthCookieSigner: """ save/restore ``environ`` entries via digially signed cookie @@ -195,7 +195,7 @@ def append(self, value): return list.append(self, str(value)) -class AuthCookieHandler(object): +class AuthCookieHandler: """ the actual handler that should be put in your middleware stack diff --git a/paste/auth/digest.py b/paste/auth/digest.py index e787fe8d..04dec155 100644 --- a/paste/auth/digest.py +++ b/paste/auth/digest.py @@ -54,7 +54,7 @@ def _split_auth_string(auth_string): prev = "%s,%s" % (prev, item) continue except AttributeError: - if prev == None: + if prev is None: prev = item continue else: @@ -78,7 +78,7 @@ def digest_password(realm, username, password): content = content.encode('utf8') return md5(content).hexdigest() -class AuthDigestAuthenticator(object): +class AuthDigestAuthenticator: """ implementation of RFC 2617 - HTTP Digest Authentication """ def __init__(self, realm, authfunc): self.nonce = {} # list to prevent replay attacks @@ -156,7 +156,7 @@ def authenticate(self, environ): if qop: assert 'auth' == qop assert nonce and nc - except: + except Exception: return self.build_authentication() ha1 = self.authfunc(environ, realm, username) return self.compute(ha1, username, response, method, authpath, @@ -164,7 +164,7 @@ def authenticate(self, environ): __call__ = authenticate -class AuthDigestHandler(object): +class AuthDigestHandler: """ middleware for HTTP Digest authentication (RFC 2617) diff --git a/paste/auth/form.py b/paste/auth/form.py index 9be82a29..9fc63f11 100644 --- a/paste/auth/form.py +++ b/paste/auth/form.py @@ -44,7 +44,7 @@ """ -class AuthFormHandler(object): +class AuthFormHandler: """ HTML-based login middleware diff --git a/paste/auth/multi.py b/paste/auth/multi.py index b378fa6c..e3516c2a 100644 --- a/paste/auth/multi.py +++ b/paste/auth/multi.py @@ -32,7 +32,7 @@ """ -class MultiHandler(object): +class MultiHandler: """ Multiple Authentication Handler diff --git a/paste/cascade.py b/paste/cascade.py index d198564e..05b672a8 100644 --- a/paste/cascade.py +++ b/paste/cascade.py @@ -40,7 +40,7 @@ def make_cascade(loader, global_conf, catch='404', **local_conf): apps = [app for name, app in apps] return Cascade(apps, catch=catch) -class Cascade(object): +class Cascade: """ Passed a list of applications, ``Cascade`` will try each of them diff --git a/paste/cgiapp.py b/paste/cgiapp.py index 04d318e5..7421def4 100644 --- a/paste/cgiapp.py +++ b/paste/cgiapp.py @@ -116,7 +116,7 @@ def __call__(self, environ, start_response): start_response(writer.status, writer.headers) return [] -class CGIWriter(object): +class CGIWriter: def __init__(self, environ, start_response): self.environ = environ diff --git a/paste/cgitb_catcher.py b/paste/cgitb_catcher.py index 11cf6330..64214467 100644 --- a/paste/cgitb_catcher.py +++ b/paste/cgitb_catcher.py @@ -10,26 +10,22 @@ from io import StringIO import sys -from paste.util import converters +from paste.util import converters, NO_DEFAULT from paste.util.cgitb_hook import Hook -class NoDefault: - ... - - class CgitbMiddleware: def __init__(self, app, global_conf=None, - display=NoDefault, + display=NO_DEFAULT, logdir=None, context=5, format="html"): self.app = app if global_conf is None: global_conf = {} - if display is NoDefault: + if display is NO_DEFAULT: display = global_conf.get('debug') if isinstance(display, str): display = converters.asbool(display) @@ -66,7 +62,7 @@ def catching_iter(self, app_iter, environ): if not error_on_close and hasattr(app_iter, 'close'): try: app_iter.close() - except: + except Exception: close_response = self.exception_handler( sys.exc_info(), environ) response += ( @@ -88,7 +84,7 @@ def exception_handler(self, exc_info, environ): def make_cgitb_middleware(app, global_conf, - display=NoDefault, + display=NO_DEFAULT, logdir=None, context=5, format='html'): @@ -108,7 +104,7 @@ def make_cgitb_middleware(app, global_conf, source code """ from paste.deploy.converters import asbool - if display is not NoDefault: + if display is not NO_DEFAULT: display = asbool(display) if 'debug' in global_conf: global_conf['debug'] = asbool(global_conf['debug']) diff --git a/paste/config.py b/paste/config.py index c5315797..c93055b0 100644 --- a/paste/config.py +++ b/paste/config.py @@ -2,8 +2,11 @@ # Written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """Paste Configuration Middleware and Objects""" + +from paste.util import NO_DEFAULT from paste.registry import RegistryManager, StackedObjectProxy + __all__ = ['DispatchingConfig', 'CONFIG', 'ConfigMiddleware'] class DispatchingConfig(StackedObjectProxy): @@ -79,7 +82,7 @@ def _current_obj(self): CONFIG = DispatchingConfig() -no_config = object() + class ConfigMiddleware(RegistryManager): """ A WSGI middleware that adds a ``paste.config`` key (by default) @@ -96,7 +99,7 @@ def __init__(self, application, config, dispatching_config=CONFIG, of the configuration `config`. """ def register_config(environ, start_response): - popped_config = environ.get(environ_key, no_config) + popped_config = environ.get(environ_key, NO_DEFAULT) current_config = environ[environ_key] = config.copy() environ['paste.registry'].register(dispatching_config, current_config) @@ -104,7 +107,7 @@ def register_config(environ, start_response): try: app_iter = application(environ, start_response) finally: - if popped_config is no_config: + if popped_config is NO_DEFAULT: environ.pop(environ_key, None) else: environ[environ_key] = popped_config diff --git a/paste/cowbell/__init__.py b/paste/cowbell/__init__.py index 5a0d22de..9acb76cf 100644 --- a/paste/cowbell/__init__.py +++ b/paste/cowbell/__init__.py @@ -6,7 +6,7 @@ SOUND = "http://www.c-eye.net/eyeon/WalkenWAVS/explorestudiospace.wav" -class MoreCowbell(object): +class MoreCowbell: def __init__(self, app): self.app = app def __call__(self, environ, start_response): diff --git a/paste/debug/debugapp.py b/paste/debug/debugapp.py index ca5730ee..14e7ef21 100755 --- a/paste/debug/debugapp.py +++ b/paste/debug/debugapp.py @@ -12,7 +12,7 @@ __all__ = ['SimpleApplication', 'SlowConsumer'] -class SimpleApplication(object): +class SimpleApplication: """ Produces a simple web page """ @@ -22,7 +22,7 @@ def __call__(self, environ, start_response): ('Content-Length', str(len(body)))]) return [body] -class SlowConsumer(object): +class SlowConsumer: """ Consumes an upload slowly... diff --git a/paste/debug/fsdiff.py b/paste/debug/fsdiff.py index 6f9ec2dd..d3ed8aca 100644 --- a/paste/debug/fsdiff.py +++ b/paste/debug/fsdiff.py @@ -25,7 +25,7 @@ __all__ = ['Diff', 'Snapshot', 'File', 'Dir', 'report_expected_diffs', 'show_diff'] -class Diff(object): +class Diff: """ Represents the difference between two snapshots @@ -201,7 +201,7 @@ def clone(self): ignore_paths=self.ignore_paths, ignore_hidden=self.ignore_hidden) -class File(object): +class File: """ Represents a single file found as the result of a command. diff --git a/paste/debug/prints.py b/paste/debug/prints.py index 8286fbc9..a698aad4 100644 --- a/paste/debug/prints.py +++ b/paste/debug/prints.py @@ -29,7 +29,7 @@ __all__ = ['PrintDebugMiddleware'] -class TeeFile(object): +class TeeFile: def __init__(self, files): self.files = files @@ -38,7 +38,7 @@ def write(self, v): for file in self.files: file.write(v) -class PrintDebugMiddleware(object): +class PrintDebugMiddleware: """ This middleware captures all the printed statements, and inlines diff --git a/paste/debug/profile.py b/paste/debug/profile.py index f069ed95..8c2bc728 100644 --- a/paste/debug/profile.py +++ b/paste/debug/profile.py @@ -18,7 +18,7 @@ __all__ = ['ProfileMiddleware', 'profile_decorator'] -class ProfileMiddleware(object): +class ProfileMiddleware: """ Middleware that profiles all requests. @@ -139,7 +139,7 @@ def replacement(*args, **kw): return replacement return decorator -class DecoratedProfile(object): +class DecoratedProfile: lock = threading.Lock() @@ -167,7 +167,7 @@ def profile(self, func, *args, **kw): start_time = time.time() try: result = prof.runcall(func, *args, **kw) - except: + except Exception: exc_info = sys.exc_info() end_time = time.time() finally: diff --git a/paste/debug/watchthreads.py b/paste/debug/watchthreads.py index 098e2de9..95e6f3aa 100644 --- a/paste/debug/watchthreads.py +++ b/paste/debug/watchthreads.py @@ -168,7 +168,7 @@ ''', name='watchthreads.page_template') -class WatchThreads(object): +class WatchThreads: """ Application that watches the threads in ``paste.httpserver``, diff --git a/paste/debug/wdg_validate.py b/paste/debug/wdg_validate.py index e7520d10..73968f3c 100644 --- a/paste/debug/wdg_validate.py +++ b/paste/debug/wdg_validate.py @@ -13,7 +13,7 @@ __all__ = ['WDGValidateMiddleware'] -class WDGValidateMiddleware(object): +class WDGValidateMiddleware: """ Middleware that checks HTML and appends messages about the validity of diff --git a/paste/errordocument.py b/paste/errordocument.py index 6dc7b068..56f1b5a6 100644 --- a/paste/errordocument.py +++ b/paste/errordocument.py @@ -60,7 +60,7 @@ def error_codes_mapper(code, message, environ, global_conf, codes): ) ) -class StatusKeeper(object): +class StatusKeeper: def __init__(self, app, status, url, headers): self.app = app self.status = status @@ -94,7 +94,7 @@ def keep_status_start_response(status, headers, exc_info=None): return [body] -class StatusBasedForward(object): +class StatusBasedForward: """ Middleware that lets you test a response against a custom mapper object to programatically determine whether to internally forward to another URL and @@ -182,7 +182,7 @@ def change_response(status, headers, exc_info=None): self.global_conf, **self.params ) - if not (new_url == None or isinstance(new_url, str)): + if not (new_url is None or isinstance(new_url, str)): raise TypeError( 'Expected the url to internally ' 'redirect to in the StatusBasedForward mapper' @@ -254,7 +254,7 @@ def custom_forward(app, mapper, global_conf=None, **kw): global_conf = {} return _StatusBasedRedirect(app, mapper, global_conf, **kw) -class _StatusBasedRedirect(object): +class _StatusBasedRedirect: """ Deprectated; use StatusBasedForward instead. """ @@ -311,7 +311,7 @@ def change_response(status, headers, exc_info=None): self.global_conf, self.kw ) - if not (new_url == None or isinstance(new_url, str)): + if not (new_url is None or isinstance(new_url, str)): raise TypeError( 'Expected the url to internally ' 'redirect to in the _StatusBasedRedirect error_mapper' @@ -322,15 +322,15 @@ def change_response(status, headers, exc_info=None): code_message.append([code, message]) return start_response(status, headers, exc_info) app_iter = self.application(environ, change_response) - except: + except Exception: try: import sys error = str(sys.exc_info()[1]) - except: + except Exception: error = '' try: code, message = code_message[0] - except: + except Exception: code, message = ['', ''] environ['wsgi.errors'].write( 'Error occurred in _StatusBasedRedirect ' diff --git a/paste/evalexception/evalcontext.py b/paste/evalexception/evalcontext.py index a7bf5d5d..05434f41 100644 --- a/paste/evalexception/evalcontext.py +++ b/paste/evalexception/evalcontext.py @@ -38,7 +38,7 @@ def exec_expr(self, s): debugger.set_continue() except KeyboardInterrupt: raise - except: + except Exception: traceback.print_exc(file=out) debugger.set_continue() finally: diff --git a/paste/evalexception/middleware.py b/paste/evalexception/middleware.py index 9e11eaa4..c62d3072 100644 --- a/paste/evalexception/middleware.py +++ b/paste/evalexception/middleware.py @@ -84,7 +84,7 @@ def simplecatcher(application): def simplecatcher_app(environ, start_response): try: return application(environ, start_response) - except: + except Exception: out = StringIO() traceback.print_exc(file=out) start_response('500 Server Error', @@ -166,7 +166,7 @@ def get_debug_count(environ): environ['paste.evalexception.debug_count'] = _next = next(debug_counter) return _next -class EvalException(object): +class EvalException: def __init__(self, application, global_conf=None, xmlhttp_key=None): @@ -301,7 +301,7 @@ def respond(self, environ, start_response): def detect_start_response(status, headers, exc_info=None): try: return start_response(status, headers, exc_info) - except: + except Exception: raise else: started.append(True) @@ -314,7 +314,7 @@ def detect_start_response(status, headers, exc_info=None): finally: if hasattr(app_iter, 'close'): app_iter.close() - except: + except Exception: exc_info = sys.exc_info() for expected in environ.get('paste.expected_exceptions', []): if isinstance(exc_info[1], expected): @@ -365,7 +365,7 @@ def exception_handler(self, exc_info, environ): debug_mode=True, simple_html_error=simple_html_error) -class DebugInfo(object): +class DebugInfo: def __init__(self, counter, exc_info, exc_data, base_path, environ, view_uri): diff --git a/paste/exceptions/collector.py b/paste/exceptions/collector.py index 9a5e42a1..83343b53 100644 --- a/paste/exceptions/collector.py +++ b/paste/exceptions/collector.py @@ -34,7 +34,7 @@ __all__ = ['collect_exception', 'ExceptionCollector'] -class ExceptionCollector(object): +class ExceptionCollector: """ Produces a data structure that can be used by formatters to @@ -235,7 +235,7 @@ def getRevision(self, globals): if revision is not None: try: revision = str(revision).strip() - except: + except Exception: revision = '???' return revision @@ -299,7 +299,7 @@ def collectLine(self, tb, extra_data): if data['supplement'].extra: for key, value in data['supplement'].extra.items(): extra_data.setdefault(key, []).append(value) - except: + except Exception: if DEBUG_EXCEPTION_FORMATTER: out = StringIO() traceback.print_exc(file=out) @@ -311,7 +311,7 @@ def collectLine(self, tb, extra_data): tbi = locals.get('__traceback_info__', None) if tbi is not None: data['traceback_info'] = str(tbi) - except: + except Exception: pass marker = [] @@ -321,7 +321,7 @@ def collectLine(self, tb, extra_data): tbh = locals.get(name, globals.get(name, marker)) if tbh is not marker: data[name[2:-2]] = tbh - except: + except Exception: pass return data @@ -373,7 +373,7 @@ def collectException(self, etype, value, tb, limit=None): new_result = decorator(result) if new_result is not None: result = new_result - except: + except Exception: pass return result @@ -390,7 +390,7 @@ def safeStr(self, obj): limit = 200 -class Bunch(object): +class Bunch: """ A generic container @@ -517,7 +517,7 @@ def collect_exception(t, v, tb, limit=None): try: blah blah - except: + except Exception: exc_data = collect_exception(*sys.exc_info()) """ return col.collectException(t, v, tb, limit=limit) diff --git a/paste/exceptions/errormiddleware.py b/paste/exceptions/errormiddleware.py index a2bbb93e..79debe35 100644 --- a/paste/exceptions/errormiddleware.py +++ b/paste/exceptions/errormiddleware.py @@ -14,12 +14,12 @@ __all__ = ['ErrorMiddleware', 'handle_exception'] -class _NoDefault(object): +class _NoDefault: def __repr__(self): return '' NoDefault = _NoDefault() -class ErrorMiddleware(object): +class ErrorMiddleware: """ Error handling middleware @@ -140,7 +140,7 @@ def __call__(self, environ, start_response): sr_checker = ResponseStartChecker(start_response) app_iter = self.application(environ, sr_checker) return self.make_catching_iter(app_iter, environ, sr_checker) - except: + except Exception: exc_info = sys.exc_info() try: for expect in environ.get('paste.expected_exceptions', []): @@ -185,7 +185,7 @@ def exception_handler(self, exc_info, environ): error_message=self.error_message, simple_html_error=simple_html_error) -class ResponseStartChecker(object): +class ResponseStartChecker: def __init__(self, start_response): self.start_response = start_response self.response_started = False @@ -194,7 +194,7 @@ def __call__(self, *args): self.response_started = True self.start_response(*args) -class CatchingIter(object): +class CatchingIter: """ A wrapper around the application iterator that will catch @@ -227,7 +227,7 @@ def next(self): return close_response else: raise StopIteration - except: + except Exception: self.closed = True close_response = self._close() exc_info = sys.exc_info() @@ -260,13 +260,13 @@ def _close(self): try: self.app_iterable.close() return None - except: + except Exception: close_response = self.error_middleware.exception_handler( sys.exc_info(), self.environ) return close_response -class Supplement(object): +class Supplement: """ This is a supplement used to display standard WSGI information in @@ -339,7 +339,7 @@ def handle_exception(exc_info, error_stream, html=True, from paste.exceptions.errormiddleware import handle_exception try: do stuff - except: + except Exception: handle_exception( sys.exc_info(), sys.stderr, html=False, ...other config...) @@ -419,7 +419,7 @@ def handle_exception(exc_info, error_stream, html=True, def send_report(rep, exc_data, html=True): try: rep.report(exc_data) - except: + except Exception: output = StringIO() traceback.print_exc(file=output) if html: diff --git a/paste/exceptions/formatter.py b/paste/exceptions/formatter.py index 8f78da6d..f6ad4470 100644 --- a/paste/exceptions/formatter.py +++ b/paste/exceptions/formatter.py @@ -14,7 +14,7 @@ def html_quote(s): return html.escape(str(s), True) -class AbstractFormatter(object): +class AbstractFormatter: general_data_order = ['object', 'source_url'] @@ -481,7 +481,7 @@ def str2html(src, strip=False, indent_subsequent=0, return _str2html(src, strip=strip, indent_subsequent=indent_subsequent, highlight_inner=highlight_inner) - except: + except Exception: return html_quote(src) def _str2html(src, strip=False, indent_subsequent=0, @@ -495,7 +495,7 @@ def _str2html(src, strip=False, indent_subsequent=0, src = pre_re.sub('', src) src = re.sub(r'^[\n\r]{0,1}', '', src) src = re.sub(r'[\n\r]{0,1}$', '', src) - except: + except Exception: src = html_quote(orig_src) lines = src.splitlines() if len(lines) == 1: diff --git a/paste/exceptions/reporter.py b/paste/exceptions/reporter.py index 369f6e74..058c63d6 100644 --- a/paste/exceptions/reporter.py +++ b/paste/exceptions/reporter.py @@ -11,7 +11,7 @@ sslerror = None from paste.exceptions import formatter -class Reporter(object): +class Reporter: def __init__(self, **conf): for name, value in conf.items(): diff --git a/paste/fileapp.py b/paste/fileapp.py index 9bde8434..677a170a 100644 --- a/paste/fileapp.py +++ b/paste/fileapp.py @@ -39,7 +39,7 @@ __all__ = ['DataApp', 'FileApp', 'DirectoryApp', 'ArchiveStore'] -class DataApp(object): +class DataApp: """ Returns an application that will send content in a single chunk, this application has support for setting cache-control and for @@ -258,7 +258,7 @@ def get(self, environ, start_response): else: return _FileIter(file, size=content_length) -class _FileIter(object): +class _FileIter: def __init__(self, file, block_size=None, size=None): self.file = file @@ -284,7 +284,7 @@ def close(self): self.file.close() -class DirectoryApp(object): +class DirectoryApp: """ Returns an application that dispatches requests to corresponding FileApps based on PATH_INFO. FileApp instances are cached. This app makes sure not to serve any files that are not in a subdirectory. @@ -315,7 +315,7 @@ def __call__(self, environ, start_response): return app(environ, start_response) -class ArchiveStore(object): +class ArchiveStore: """ Returns an application that serves up a DataApp for items requested in a given zip or tar archive. diff --git a/paste/fixture.py b/paste/fixture.py index ab613a2a..f253ced4 100644 --- a/paste/fixture.py +++ b/paste/fixture.py @@ -20,13 +20,13 @@ import shlex import re import subprocess -from urllib.parse import urlencode from urllib import parse as urlparse +from urllib.parse import urlencode from http.cookies import BaseCookie -from paste import wsgilib -from paste import lint +from paste import lint, wsgilib from paste.response import HeaderDict +from paste.util import NO_DEFAULT def ensure_binary(s): if isinstance(s, bytes): @@ -48,15 +48,12 @@ def tempnam_no_warning(*args): """ return os.tempnam(*args) -class NoDefault(object): - pass - def sorted(l): l = list(l) l.sort() return l -class Dummy_smtplib(object): +class Dummy_smtplib: existing = None @@ -97,7 +94,7 @@ class AppError(Exception): pass -class TestApp(object): +class TestApp: __test__ = False # Ignore with pytest test collection. @@ -479,7 +476,7 @@ def _make_response(self, resp, total_time): return TestResponse(self, status, headers, body, errors, total_time) -class CaptureStdout(object): +class CaptureStdout: def __init__(self, actual): self.captured = io.StringIO() @@ -500,7 +497,7 @@ def getvalue(self): return self.captured.getvalue() -class TestResponse(object): +class TestResponse: __test__ = False # Ignore with pytest test collection. @@ -586,7 +583,7 @@ def _parse_forms(self): if form.id: forms[form.id] = form - def header(self, name, default=NoDefault): + def header(self, name, default=NO_DEFAULT): """ Returns the named header; an error if there is not exactly one matching header (unless you give a default -- always an error @@ -600,7 +597,7 @@ def header(self, name, default=NoDefault): % (name, found, value)) found = value if found is None: - if default is NoDefault: + if default is NO_DEFAULT: raise KeyError( "No header found: %r (from %s)" % (name, ', '.join([n for n, v in self.headers]))) @@ -888,7 +885,7 @@ def showbrowser(self): webbrowser.open_new(url) -class TestRequest(object): +class TestRequest: __test__ = False # Ignore with pytest test collection. @@ -925,7 +922,7 @@ def __init__(self, url, environ, expect_errors=False): self.expect_errors = expect_errors -class Form(object): +class Form: """ This object represents a form that has been found in a page. @@ -1089,13 +1086,13 @@ def set(self, name, value, index=None): field = fields[index] field.value = value - def get(self, name, index=None, default=NoDefault): + def get(self, name, index=None, default=NO_DEFAULT): """ Get the named/indexed field object, or ``default`` if no field is found. """ fields = self.fields.get(name) - if fields is None and default is not NoDefault: + if fields is None and default is not NO_DEFAULT: return default if index is None: return self[name] @@ -1160,7 +1157,7 @@ def _parse_attrs(text): attrs[attr_name] = attr_body return attrs -class Field(object): +class Field: """ Field object. @@ -1329,7 +1326,7 @@ def value_if_submitted(self): ############################################################ -class TestFileEnvironment(object): +class TestFileEnvironment: """ This represents an environment in which files will be written, and @@ -1521,7 +1518,7 @@ def writefile(self, path, content=None, f.close() return FoundFile(self.base_path, path) -class ProcResult(object): +class ProcResult: """ Represents the results of running a command in @@ -1600,7 +1597,7 @@ def __str__(self): s.append(t) return '\n'.join(s) -class FoundFile(object): +class FoundFile: """ Represents a single file found as the result of a command. @@ -1660,7 +1657,7 @@ def __repr__(self): self.__class__.__name__, self.base_path, self.path) -class FoundDir(object): +class FoundDir: """ Represents a directory created by a command. diff --git a/paste/flup_session.py b/paste/flup_session.py index 6f5c7505..390d2c68 100644 --- a/paste/flup_session.py +++ b/paste/flup_session.py @@ -16,19 +16,18 @@ data. """ -from paste import httpexceptions -from paste import wsgilib +from paste import httpexceptions, wsgilib +from paste.util import NO_DEFAULT + import flup.middleware.session + flup_session = flup.middleware.session # This is a dictionary of existing stores, keyed by a tuple of # store type and parameters store_cache = {} -class NoDefault(object): - pass - -class SessionMiddleware(object): +class SessionMiddleware: session_classes = { 'memory': (flup_session.MemorySessionStore, @@ -45,12 +44,12 @@ class SessionMiddleware(object): def __init__(self, app, global_conf=None, - session_type=NoDefault, - cookie_name=NoDefault, + session_type=NO_DEFAULT, + cookie_name=NO_DEFAULT, **store_config ): self.application = app - if session_type is NoDefault: + if session_type is NO_DEFAULT: session_type = global_conf.get('session_type', 'disk') self.session_type = session_type try: @@ -65,7 +64,7 @@ def __init__(self, app, value = coercer(store_config.get(config_name, default)) kw[kw_name] = value self.store = self.store_class(**kw) - if cookie_name is NoDefault: + if cookie_name is NO_DEFAULT: cookie_name = global_conf.get('session_cookie', '_SID_') self.cookie_name = cookie_name @@ -87,15 +86,15 @@ def cookie_start_response(status, headers, exc_info=None): e.headers = dict(headers) service.close() raise - except: + except Exception: service.close() raise return wsgilib.add_close(app_iter, service.close) def make_session_middleware(app, global_conf, - session_type=NoDefault, - cookie_name=NoDefault, + session_type=NO_DEFAULT, + cookie_name=NO_DEFAULT, **store_config): """ Wraps the application in a session-managing middleware. diff --git a/paste/gzipper.py b/paste/gzipper.py index fa55eeaa..2ccc2a50 100644 --- a/paste/gzipper.py +++ b/paste/gzipper.py @@ -16,10 +16,10 @@ from paste.response import header_value, remove_header from paste.httpheaders import CONTENT_LENGTH -class GzipOutput(object): +class GzipOutput: pass -class middleware(object): +class middleware: def __init__(self, application, compress_level=6): self.application = application @@ -41,7 +41,7 @@ def __call__(self, environ, start_response): return response.write() -class GzipResponse(object): +class GzipResponse: def __init__(self, start_response, compress_level): self.start_response = start_response diff --git a/paste/httpexceptions.py b/paste/httpexceptions.py index 3d7dfeac..083c16fe 100644 --- a/paste/httpexceptions.py +++ b/paste/httpexceptions.py @@ -603,7 +603,7 @@ def get_exception(code): ## Middleware implementation: ############################################################ -class HTTPExceptionHandler(object): +class HTTPExceptionHandler: """ catches exceptions and turns them into proper HTTP responses diff --git a/paste/httpheaders.py b/paste/httpheaders.py index a1e91a9b..36ea6af5 100644 --- a/paste/httpheaders.py +++ b/paste/httpheaders.py @@ -170,7 +170,7 @@ def update(self, environ, value): _headers = {} -class HTTPHeader(object): +class HTTPHeader: """ an HTTP header @@ -1008,7 +1008,7 @@ def compose(self, digest=None, basic=None, username=None, password=None, auth.add_password(realm, path, username, password) (token, challenge) = challenge.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) - class FakeRequest(object): + class FakeRequest: @property def full_url(self): return path diff --git a/paste/httpserver.py b/paste/httpserver.py index f8539ec0..5cecb756 100755 --- a/paste/httpserver.py +++ b/paste/httpserver.py @@ -54,7 +54,7 @@ def _get_headers(headers, k): return headers.getheaders(k) # Python 2 - mimetools.Message -class ContinueHook(object): +class ContinueHook: """ When a client request includes a 'Expect: 100-continue' header, then it is the responsibility of the server to send 100 Continue when it @@ -313,7 +313,7 @@ def wsgi_execute(self, environ=None): except socket.error as exce: self.wsgi_connection_drop(exce, environ) return - except: + except Exception: if not self.wsgi_headers_sent: error_msg = "Internal Server Error\n" self.wsgi_curr_headers = ( @@ -346,7 +346,7 @@ def __init__(self, server_address, RequestHandlerClass, self.socket.listen(request_queue_size) else: - class _ConnFixer(object): + class _ConnFixer: """ wraps a socket connection so it implements makefile """ def __init__(self, conn): self.__conn = conn @@ -466,7 +466,7 @@ def address_string(self): """ return '' -class LimitedLengthFile(object): +class LimitedLengthFile: def __init__(self, file, length): self.file = file self.length = length @@ -528,7 +528,7 @@ def tell(self): pass return self._consumed -class ThreadPool(object): +class ThreadPool: """ Generic thread pool with a queue of callables to consume. @@ -800,7 +800,7 @@ def kill_hung_threads(self): try: import pprint info_desc = pprint.pformat(info) - except: + except Exception: out = io.StringIO() traceback.print_exc(file=out) info_desc = 'Error:\n%s' % out.getvalue() @@ -899,7 +899,7 @@ def worker_thread_callback(self, message=None): try: try: runnable() - except: + except Exception: # We are later going to call sys.exc_clear(), # removing all remnants of any exception, so # we should log it now. But ideally no @@ -1018,7 +1018,7 @@ def notify_problem(self, msg, subject=None, spawn_thread=True): ] try: system = ' '.join(os.uname()) - except: + except Exception: system = '(unknown)' body = ( "An error has occurred in the paste.httpserver.ThreadPool\n" @@ -1044,7 +1044,7 @@ def notify_problem(self, msg, subject=None, spawn_thread=True): server.quit() print('email sent to', error_emails, message) -class ThreadPoolMixIn(object): +class ThreadPoolMixIn: """ Mix-in class to process requests from a thread pool """ diff --git a/paste/lint.py b/paste/lint.py index 0e2093ce..5c04f0fe 100644 --- a/paste/lint.py +++ b/paste/lint.py @@ -176,7 +176,7 @@ def start_response_wrapper(*args, **kw): return lint_app -class InputWrapper(object): +class InputWrapper: def __init__(self, wsgi_input): self.input = wsgi_input @@ -210,7 +210,7 @@ def __iter__(self): def close(self): assert 0, "input.close() must not be called" -class ErrorWrapper(object): +class ErrorWrapper: def __init__(self, wsgi_errors): self.errors = wsgi_errors @@ -229,7 +229,7 @@ def writelines(self, seq): def close(self): assert 0, "errors.close() must not be called" -class WriteWrapper(object): +class WriteWrapper: def __init__(self, wsgi_writer): self.writer = wsgi_writer @@ -238,7 +238,7 @@ def __call__(self, s): assert isinstance(s, bytes) self.writer(s) -class PartialIteratorWrapper(object): +class PartialIteratorWrapper: def __init__(self, wsgi_iterator): self.iterator = wsgi_iterator @@ -247,7 +247,7 @@ def __iter__(self): # We want to make sure __iter__ is called return IteratorWrapper(self.iterator) -class IteratorWrapper(object): +class IteratorWrapper: def __init__(self, wsgi_iterator, check_start_response): self.original_iterator = wsgi_iterator diff --git a/paste/modpython.py b/paste/modpython.py index a84f7b2d..7e22758e 100644 --- a/paste/modpython.py +++ b/paste/modpython.py @@ -1,4 +1,4 @@ -"""WSGI Paste wrapper for mod_python. Requires Python 2.2 or greater. +"""WSGI Paste wrapper for mod_python. Example httpd.conf section for a Paste app with an ini file:: @@ -53,11 +53,11 @@ try: from mod_python import apache -except: - pass +except ImportError: + apache = None from paste.deploy import loadapp -class InputWrapper(object): +class InputWrapper: def __init__(self, req): self.req = req @@ -83,7 +83,7 @@ def __iter__(self): line = self.readline() -class ErrorWrapper(object): +class ErrorWrapper: def __init__(self, req): self.req = req @@ -102,7 +102,7 @@ def writelines(self, seq): "when running a version of mod_python < 3.1") -class Handler(object): +class Handler: def __init__(self, req): self.started = False @@ -163,7 +163,7 @@ def run(self, application): self.request.set_content_length(0) if hasattr(result, 'close'): result.close() - except: + except Exception: traceback.print_exc(None, self.environ['wsgi.errors']) if not self.started: self.request.status = 500 diff --git a/paste/pony.py b/paste/pony.py index fce6aa88..3aae96a5 100644 --- a/paste/pony.py +++ b/paste/pony.py @@ -25,7 +25,7 @@ """ -class PonyMiddleware(object): +class PonyMiddleware: def __init__(self, application): self.application = application diff --git a/paste/progress.py b/paste/progress.py index 57bf0bd1..0ae21b1b 100755 --- a/paste/progress.py +++ b/paste/progress.py @@ -40,7 +40,7 @@ REQUEST_STARTED = 'paste.request_started' REQUEST_FINISHED = 'paste.request_finished' -class _ProgressFile(object): +class _ProgressFile: """ This is the input-file wrapper used to record the number of ``paste.bytes_received`` for the given request. @@ -77,7 +77,7 @@ def readlines(self, hint=None): self._ProgressFile_environ[ENVIRON_RECEIVED] += len(chunk) return chunk -class UploadProgressMonitor(object): +class UploadProgressMonitor: """ monitors and reports on the status of uploads in progress @@ -154,7 +154,7 @@ def finalizer(exc_info=None): def uploads(self): return self.monitor -class UploadProgressReporter(object): +class UploadProgressReporter: """ reports on the progress of uploads for a given user diff --git a/paste/proxy.py b/paste/proxy.py index 513a0e4f..3de63897 100644 --- a/paste/proxy.py +++ b/paste/proxy.py @@ -49,7 +49,7 @@ 'upgrade', ) -class Proxy(object): +class Proxy: def __init__(self, address, allowed_request_methods=(), suppress_http_headers=()): @@ -154,7 +154,7 @@ def make_proxy(global_conf, address, allowed_request_methods="", suppress_http_headers=suppress_http_headers) -class TransparentProxy(object): +class TransparentProxy: """ A proxy that sends the request just as it was given, including diff --git a/paste/recursive.py b/paste/recursive.py index 897d6f39..b3fda7b3 100644 --- a/paste/recursive.py +++ b/paste/recursive.py @@ -33,7 +33,7 @@ class RecursionLoop(AssertionError): # Subclasses AssertionError for legacy reasons """Raised when a recursion enters into a loop""" -class CheckForRecursionMiddleware(object): +class CheckForRecursionMiddleware: def __init__(self, app, env): self.app = app self.env = env @@ -50,7 +50,7 @@ def __call__(self, environ, start_response): old_path_info.append(self.env.get('PATH_INFO', '')) return self.app(environ, start_response) -class RecursiveMiddleware(object): +class RecursiveMiddleware: """ A WSGI middleware that allows for recursive and forwarded calls. @@ -205,7 +205,7 @@ def __init__( self.path_info = url # Base middleware - class ForwardRequestExceptionMiddleware(object): + class ForwardRequestExceptionMiddleware: def __init__(self, app): self.app = app @@ -238,7 +238,7 @@ def __call__(self, environ_, start_response): else: self.factory = factory -class Recursive(object): +class Recursive: def __init__(self, application, environ, start_response): self.application = application @@ -333,7 +333,7 @@ def start_response(status, headers, exc_info=None): response.close() return response -class IncludedResponse(object): +class IncludedResponse: def __init__(self): self.headers = None @@ -381,7 +381,7 @@ def start_response(status, headers, exc_info=None): response.app_iter = app_iter return response -class IncludedAppIterResponse(object): +class IncludedAppIterResponse: def __init__(self): self.status = None diff --git a/paste/registry.py b/paste/registry.py index 02623d48..bcf4ebde 100644 --- a/paste/registry.py +++ b/paste/registry.py @@ -34,7 +34,7 @@ app = RegistryManager(yourapp) #inside your wsgi app - class yourapp(object): + class yourapp: def __call__(self, environ, start_response): obj = someobject # The request-local object you want to access # via yourpackage.myglobal @@ -87,16 +87,15 @@ def somefunc(): one should consider the proxy object to be causing slow-downs. This section is provided solely in the extremely rare case that it is an issue so that a quick way to work around it is documented. - """ + +from paste.util import NO_DEFAULT import paste.util.threadinglocal as threadinglocal __all__ = ['StackedObjectProxy', 'RegistryManager', 'StackedObjectRestorer', 'restorer'] -class NoDefault(object): pass - -class StackedObjectProxy(object): +class StackedObjectProxy: """Track an object instance internally using a stack The StackedObjectProxy proxies access to an object internally using a @@ -108,7 +107,7 @@ class StackedObjectProxy(object): objects can be removed with _pop_object. """ - def __init__(self, default=NoDefault, name="Default"): + def __init__(self, default=NO_DEFAULT, name="Default"): """Create a new StackedObjectProxy If a default is given, its used in every thread if no other object @@ -117,7 +116,7 @@ def __init__(self, default=NoDefault, name="Default"): """ self.__dict__['____name__'] = name self.__dict__['____local__'] = threadinglocal.local() - if default is not NoDefault: + if default is not NO_DEFAULT: self.__dict__['____default_object__'] = default def __dir__(self): @@ -190,8 +189,8 @@ def _current_obj(self): if objects: return objects[-1] else: - obj = self.__dict__.get('____default_object__', NoDefault) - if obj is not NoDefault: + obj = self.__dict__.get('____default_object__', NO_DEFAULT) + if obj is not NO_DEFAULT: return obj else: raise TypeError( @@ -277,7 +276,7 @@ def _pop_object_restoration(self, obj=None): ('%s\n(StackedObjectRestorer restoration enabled)' % \ _pop_object.__doc__) -class Registry(object): +class Registry: """Track objects and stacked object proxies for removal The Registry object is instantiated a single time for the request no @@ -351,7 +350,7 @@ def cleanup(self): stacked._pop_object(obj) self.reglist.pop() -class RegistryManager(object): +class RegistryManager: """Creates and maintains a Registry context RegistryManager creates a new registry context for the registration of @@ -395,7 +394,7 @@ def __call__(self, environ, start_response): restorer.save_registry_state(environ) reg.cleanup() raise - except: + except Exception: # Save state for EvalException if it's present if environ.get('paste.evalexception'): restorer.save_registry_state(environ) @@ -426,7 +425,7 @@ def streaming_iter(self, reg, environ, start_response): restorer.save_registry_state(environ) reg.cleanup() raise - except: + except Exception: # Save state for EvalException if it's present if environ.get('paste.evalexception'): restorer.save_registry_state(environ) @@ -436,7 +435,7 @@ def streaming_iter(self, reg, environ, start_response): reg.cleanup() -class StackedObjectRestorer(object): +class StackedObjectRestorer: """Track StackedObjectProxies and their proxied objects for automatic restoration within EvalException's interactive debugger. diff --git a/paste/reloader.py b/paste/reloader.py index 97440ac7..1f2da426 100644 --- a/paste/reloader.py +++ b/paste/reloader.py @@ -61,7 +61,7 @@ def install(poll_interval=1): t.daemon = True t.start() -class Monitor(object): +class Monitor: instances = [] global_extra_files = [] @@ -92,7 +92,7 @@ def check_reload(self): for file_callback in self.file_callbacks: try: filenames.extend(file_callback()) - except: + except Exception: print("Error calling paste.reloader callback %r:" % file_callback, file=sys.stderr) traceback.print_exc() diff --git a/paste/session.py b/paste/session.py index 09f6c196..dad7669c 100644 --- a/paste/session.py +++ b/paste/session.py @@ -39,8 +39,8 @@ from hashlib import md5 except ImportError: from md5 import md5 -from paste import wsgilib -from paste import request +from paste import request, wsgilib +from paste.util import NO_DEFAULT class SessionMiddleware: @@ -76,7 +76,7 @@ def close(): return wsgilib.add_start_close(app_iter, start, close) -class SessionFactory(object): +class SessionFactory: def __init__(self, environ, cookie_name='_SID_', @@ -175,7 +175,7 @@ def close(self): cleaning_up = False cleanup_cycle = datetime.timedelta(seconds=15*60) #15 min -class FileSession(object): +class FileSession: def __init__(self, sid, create=False, session_file_path=tempfile.gettempdir(), chmod=None, @@ -272,25 +272,21 @@ def clean_up(self): last_cleanup = now t = threading.Thread(target=self._clean_up) t.start() - except: + except Exception: # Normally _clean_up should set cleaning_up # to false, but if something goes wrong starting # it... cleaning_up = False raise -class _NoDefault(object): - def __repr__(self): - return '' -NoDefault = _NoDefault() def make_session_middleware( app, global_conf, - session_expiration=NoDefault, - expiration=NoDefault, - cookie_name=NoDefault, - session_file_path=NoDefault, - chmod=NoDefault): + session_expiration=NO_DEFAULT, + expiration=NO_DEFAULT, + cookie_name=NO_DEFAULT, + session_file_path=NO_DEFAULT, + chmod=NO_DEFAULT): """ Adds a middleware that handles sessions for your applications. The session is a peristent dictionary. To get this dictionary @@ -321,17 +317,17 @@ def make_session_middleware( Each of these also takes from the global configuration. cookie_name and chmod take from session_cookie_name and session_chmod """ - if session_expiration is NoDefault: + if session_expiration is NO_DEFAULT: session_expiration = global_conf.get('session_expiration', 60*12) session_expiration = int(session_expiration) - if expiration is NoDefault: + if expiration is NO_DEFAULT: expiration = global_conf.get('expiration', 60*48) expiration = int(expiration) - if cookie_name is NoDefault: + if cookie_name is NO_DEFAULT: cookie_name = global_conf.get('session_cookie_name', '_SID_') - if session_file_path is NoDefault: + if session_file_path is NO_DEFAULT: session_file_path = global_conf.get('session_file_path', '/tmp') - if chmod is NoDefault: + if chmod is NO_DEFAULT: chmod = global_conf.get('session_chmod', None) return SessionMiddleware( app, session_expiration=session_expiration, diff --git a/paste/transaction.py b/paste/transaction.py index 1347acd8..625ba355 100644 --- a/paste/transaction.py +++ b/paste/transaction.py @@ -16,7 +16,7 @@ from paste.httpexceptions import HTTPException from wsgilib import catch_errors -class TransactionManagerMiddleware(object): +class TransactionManagerMiddleware: def __init__(self, application): self.application = application @@ -29,7 +29,7 @@ def __call__(self, environ, start_response): error_callback=manager.error, ok_callback=manager.finish) -class Manager(object): +class Manager: def __init__(self): self.aborted = False @@ -50,7 +50,7 @@ def finish(self): trans.commit() -class ConnectionFactory(object): +class ConnectionFactory: """ Provides a callable interface for connecting to ADBAPI databases in a WSGI style (using the environment). More advanced connection @@ -96,7 +96,7 @@ def finalizer(exc_info=None): else: try: conn.rollback() - except: + except Exception: # TODO: check if rollback has already happened return conn.close() diff --git a/paste/urlmap.py b/paste/urlmap.py index 8ef1da05..ba7928e8 100644 --- a/paste/urlmap.py +++ b/paste/urlmap.py @@ -213,7 +213,7 @@ def __call__(self, environ, start_response): return self.not_found_application(environ, start_response) -class PathProxyURLMap(object): +class PathProxyURLMap: """ This is a wrapper for URLMap that catches any strings that diff --git a/paste/urlparser.py b/paste/urlparser.py index 1cba0d4d..2210b22e 100644 --- a/paste/urlparser.py +++ b/paste/urlparser.py @@ -19,16 +19,12 @@ from paste import fileapp from paste.util import import_string from paste import httpexceptions -from paste.util import converters +from paste.util import converters, NO_DEFAULT from .httpheaders import ETAG __all__ = ['URLParser', 'StaticURLParser', 'PkgResourcesParser'] -class NoDefault: - pass - - class URLParser: """ @@ -84,15 +80,15 @@ class URLParser: parsers_by_directory = {} # This is lazily initialized - init_module = NoDefault + init_module = NO_DEFAULT global_constructors = {} def __init__(self, global_conf, directory, base_python_name, - index_names=NoDefault, - hide_extensions=NoDefault, - ignore_extensions=NoDefault, + index_names=NO_DEFAULT, + hide_extensions=NO_DEFAULT, + ignore_extensions=NO_DEFAULT, constructors=None, **constructor_conf): """ @@ -115,15 +111,15 @@ def __init__(self, global_conf, self.base_python_name = base_python_name # This logic here should be deprecated since it is in # make_url_parser - if index_names is NoDefault: + if index_names is NO_DEFAULT: index_names = global_conf.get( 'index_names', ('index', 'Index', 'main', 'Main')) self.index_names = converters.aslist(index_names) - if hide_extensions is NoDefault: + if hide_extensions is NO_DEFAULT: hide_extensions = global_conf.get( 'hide_extensions', ('.pyc', '.bak', '.py~', '.pyo')) self.hide_extensions = converters.aslist(hide_extensions) - if ignore_extensions is NoDefault: + if ignore_extensions is NO_DEFAULT: ignore_extensions = global_conf.get( 'ignore_extensions', ()) self.ignore_extensions = converters.aslist(ignore_extensions) @@ -144,7 +140,7 @@ def __init__(self, global_conf, def __call__(self, environ, start_response): environ['paste.urlparser.base_python_name'] = self.base_python_name - if self.init_module is NoDefault: + if self.init_module is NO_DEFAULT: self.init_module = self.find_init_module(environ) path_info = environ.get('PATH_INFO', '') if not path_info: @@ -421,7 +417,7 @@ def make_py(parser, environ, filename): URLParser.register_constructor('.py', make_py) -class StaticURLParser(object): +class StaticURLParser: """ Like ``URLParser`` but only serves static files. diff --git a/paste/util/PySourceColor.py b/paste/util/PySourceColor.py index 3d7f5cc5..02d9af95 100644 --- a/paste/util/PySourceColor.py +++ b/paste/util/PySourceColor.py @@ -1,4 +1,3 @@ -# -*- coding: Latin-1 -*- """ PySourceColor: color Python source code """ @@ -182,10 +181,12 @@ def / name __date__ = '25 April 2005' __author__ = "M.E.Farmer Jr." __credits__ = '''This was originally based on a python recipe -submitted by Jürgen Hermann to ASPN. Now based on the voices in my head. +submitted by Jürgen Hermann to ASPN. Now based on the voices in my head. M.E.Farmer 2004, 2005 Python license ''' + +import io import os import sys import time @@ -195,7 +196,7 @@ def / name import token import tokenize import traceback -from io import StringIO + # Do not edit NAME = token.NAME NUMBER = token.NUMBER @@ -612,7 +613,7 @@ def Usage(): saves it as pystyle.css in the same directory. html markup will silently ignore this flag. -H, --header - Opional-> add a page header to the top of the output + Optional-> add a page header to the top of the output -H Builtin header (name,date,hrule) --header @@ -621,7 +622,7 @@ def Usage(): and must handle its own font colors. ex. --header c:/tmp/header.txt -F, --footer - Opional-> add a page footer to the bottom of the output + Optional-> add a page footer to the bottom of the output -F Builtin footer (hrule,name,date) --footer @@ -664,7 +665,7 @@ def Usage(): python PySourceColor.py -i- -o c:/pydoc.py.html -s < c:/Python22/my.py _____________________________________________________________________________ """ - print(doc % (__version__)) + print(doc % (__version__,)) sys.exit(1) ###################################################### Command line interface @@ -732,7 +733,7 @@ def cli(): if o in ["-c", "--color"]: try: colorscheme = globals().get(a.lower()) - except: + except Exception: traceback.print_exc() Usage() if test: @@ -765,7 +766,7 @@ def cli(): str2file(sys.stdin.read(), outfile=output, show=show, markup=markup, header=header, footer=footer, linenumbers=linenumbers, form=form) - except: + except Exception: traceback.print_exc() Usage() else: @@ -781,7 +782,6 @@ def cli(): footer=footer, linenumbers=linenumbers, form=form) else: raise PathError('File does not exists!') - Usage() ######################################################### Simple markup tests @@ -841,7 +841,7 @@ def LlamasRLumpy(): """ u""" ============================= -A Møøse once bit my sister... +A Møøse once bit my sister... ============================= """ ## Relax, this won't hurt a bit, just a simple, painless procedure, @@ -849,12 +849,12 @@ def LlamasRLumpy(): m = {'three':'1','won':'2','too':'3'} o = r'fishy\fishy\fishy/fish\oh/where/is\my/little\..' python = uR""" - No realli! She was Karving her initials øn the møøse with the sharpened end - of an interspace tøøthbrush given her by Svenge - her brother-in-law -an Oslo - dentist and star of many Norwegian møvies: "The Høt Hands of an Oslo - Dentist", "Fillings of Passion", "The Huge Mølars of Horst Nordfink"...""" + No realli! She was Karving her initials øn the møøse with the sharpened end + of an interspace tøøthbrush given her by Svenge - her brother-in-law -an Oslo + dentist and star of many Norwegian møvies: "The Høt Hands of an Oslo + Dentist", "Fillings of Passion", "The Huge Mølars of Horst Nordfink"...""" RU"""142 MEXICAN WHOOPING LLAMAS"""#<-Can you fit 142 llamas in a red box? - n = u' HERMSGERVØRDENBRØTBØRDA ' + """ YUTTE """ + n = u' HERMSGERVØRDENBRØTBØRDA ' + """ YUTTE """ t = """SAMALLNIATNUOMNAIRODAUCE"""+"DENIARTYLLAICEPS04" ## We apologise for the fault in the ## comments. Those responsible have been @@ -891,7 +891,7 @@ def str2stdout(sourcestring, colors=None, title='', markup='html', header=header, footer=footer, linenumbers=linenumbers).format(form) -def path2stdout(sourcepath, title='', colors=None, markup='html', +def path2stdout(sourcepath, colors=None, markup='html', header=None, footer=None, linenumbers=0, form=None): """Converts code(file) to colorized HTML. Writes to stdout. @@ -912,7 +912,7 @@ def str2html(sourcestring, colors=None, title='', form='code',or'snip' (for "
yourcode
" only) colors=null,mono,lite,dark,dark2,idle,or pythonwin """ - stringIO = StringIO.StringIO() + stringIO = io.StringIO() Parser(sourcestring, colors=colors, title=title, out=stringIO, markup=markup, header=header, footer=footer, linenumbers=linenumbers).format(form) @@ -924,19 +924,19 @@ def str2css(sourcestring, colors=None, title='', linenumbers=0, form=None): """Converts a code string to colorized CSS/HTML. Returns CSS/HTML string - If form != None then this will return (stylesheet_str, code_str) + If form is not None then this will return (stylesheet_str, code_str) colors=null,mono,lite,dark,dark2,idle,or pythonwin """ if markup.lower() not in ['css' ,'xhtml']: markup = 'css' - stringIO = StringIO.StringIO() + stringIO = io.StringIO() parse = Parser(sourcestring, colors=colors, title=title, out=stringIO, markup=markup, header=header, footer=footer, linenumbers=linenumbers) parse.format(form) stringIO.seek(0) - if form != None: + if form is not None: return parse._sendCSSStyle(external=1), stringIO.read() else: return None, stringIO.read() @@ -961,7 +961,7 @@ def str2file(sourcestring, outfile, colors=None, title='', makes no attempt at correcting bad pathnames """ - css , html = str2markup(sourcestring, colors=colors, title='', + css , html = str2markup(sourcestring, colors=colors, title=title, markup=markup, header=header, footer=footer, linenumbers=linenumbers, form=form) # write html @@ -969,7 +969,7 @@ def str2file(sourcestring, outfile, colors=None, title='', f.writelines(html) f.close() #write css - if css != None and dosheet: + if css is not None and dosheet: dir = os.path.dirname(outfile) outcss = os.path.join(dir,'pystyle.css') f = open(outcss,'wt') @@ -986,7 +986,7 @@ def path2html(sourcepath, colors=None, markup='html', form='code',or'snip' (for "
yourcode
" only) colors=null,mono,lite,dark,dark2,idle,or pythonwin """ - stringIO = StringIO.StringIO() + stringIO = io.StringIO() sourcestring = open(sourcepath).read() Parser(sourcestring, colors, title=sourcepath, out=stringIO, markup=markup, header=header, footer=footer, @@ -1014,9 +1014,9 @@ def convert(source, outdir=None, colors=None, # Then we need to colorize them with path2file else: fileList = walkdir(source) - if fileList != None: + if fileList is not None: # make sure outdir is a dir - if outdir != None: + if outdir is not None: if os.path.splitext(outdir)[1] != '': outdir = os.path.split(outdir)[0] for item in fileList: @@ -1032,7 +1032,7 @@ def path2file(sourcePath, out=None, colors=None, show=0, header=None, footer=None, linenumbers=0, count=1): """ Converts python source to html file""" # If no outdir is given we use the sourcePath - if out == None:#this is a guess + if out is None:#this is a guess htmlPath = sourcePath + '.html' else: # If we do give an out_dir, and it does @@ -1095,7 +1095,8 @@ def tagreplace(sourcestr, colors=lite, markup='xhtml', end = sourcestr[dataend+len(tagend):] sourcestr = ''.join([start,data,end]) else: - raise InputError('Tag mismatch!\nCheck %s,%s tags'%tagstart,tagend) + raise InputError( + 'Tag mismatch!\nCheck %s,%s tags'%(tagstart,tagend)) if not dosheet: css = None return css, sourcestr @@ -1107,7 +1108,7 @@ def pageconvert(path, out=None, colors=lite, markup='xhtml', linenumbers=0, that is written in a webpage enclosed in tags. """ - if out == None: + if out is None: out = os.path.dirname(path) infile = open(path, 'r').read() css,page = tagreplace(sourcestr=infile,colors=colors, @@ -1119,7 +1120,7 @@ def pageconvert(path, out=None, colors=lite, markup='xhtml', linenumbers=0, if not os.path.exists(newpath): try: os.makedirs(os.path.dirname(newpath)) - except: + except Exception: pass#traceback.print_exc() #Usage() y = open(newpath, 'w') @@ -1134,7 +1135,7 @@ def pageconvert(path, out=None, colors=lite, markup='xhtml', linenumbers=0, if show: try: os.startfile(newpath) - except: + except Exception: traceback.print_exc() return newpath else: @@ -1143,30 +1144,18 @@ def pageconvert(path, out=None, colors=lite, markup='xhtml', linenumbers=0, ##################################################################### helpers def walkdir(dir): - """Return a list of .py and .pyw files from a given directory. - - This function can be written as a generator Python 2.3, or a genexp - in Python 2.4. But 2.2 and 2.1 would be left out.... - """ + """Return a list of .py and .pyw files from a given directory.""" # Get a list of files that match *.py* - GLOB_PATTERN = os.path.join(dir, "*.[p][y]*") - pathlist = glob.glob(GLOB_PATTERN) + pathlist = glob.glob(os.path.join(dir, "*.[p][y]*")) # Now filter out all but py and pyw - filterlist = [x for x in pathlist - if x.endswith('.py') - or x.endswith('.pyw')] - if filterlist != []: - # if we have a list send it - return filterlist - else: - return None + return [x for x in pathlist if x.endswith(('.py', '.pyw'))] or None def showpage(path): """Helper function to open webpages""" try: import webbrowser webbrowser.open_new(os.path.abspath(path)) - except: + except Exception: traceback.print_exc() def _printinfo(message, quiet): @@ -1212,14 +1201,14 @@ def __init__(self, msg): ########################################################## Python code parser -class Parser(object): +class Parser: """MoinMoin python parser heavily chopped :)""" def __init__(self, raw, colors=None, title='', out=sys.stdout, markup='html', header=None, footer=None, linenumbers=0): """Store the source text & set some flags""" - if colors == None: + if colors is None: colors = defaultColors self.raw = raw.expandtabs().rstrip() self.title = os.path.basename(title) @@ -1277,9 +1266,7 @@ def format(self, form=None): lines = self.raw.splitlines(0) for l in lines: # span and div escape for customizing and embedding raw text - if (l.startswith('#$#') - or l.startswith('#%#') - or l.startswith('#@#')): + if l.startswith(('#$#', '#%#', '#@#')): newlines.append(l) else: # kludge for line spans in css,xhtml @@ -1292,13 +1279,14 @@ def format(self, form=None): # Gather lines while 1: pos = self.raw.find('\n', pos) + 1 - if not pos: break + if not pos: + break self.lines.append(pos) self.lines.append(len(self.raw)) # Wrap text in a filelike object self.pos = 0 - text = StringIO.StringIO(self.raw) + text = io.StringIO(self.raw) # Markup start if self.addEnds: @@ -1310,13 +1298,13 @@ def format(self, form=None): ## function for each token till done. # Parse the source and write out the results. try: - tokenize.tokenize(text.readline, self) - except tokenize.TokenError as ex: - msg = ex[0] - line = ex[1][0] + for token in tokenize.generate_tokens(text.readline): + self(*token) + except tokenize.TokenError as error: + msg = error.args[0] + line = error.args[1][0] self.out.write("

ERROR: %s

%s\n"% (msg, self.raw[self.lines[line]:])) - #traceback.print_exc() # Markup end if self.addEnds: @@ -1351,7 +1339,7 @@ def __call__(self, toktype, toktext, srow_col, erow_col, line): if newpos > oldpos: if self.raw[oldpos:newpos].isspace(): # consume a single space after linestarts and linenumbers - # had to have them so tokenizer could seperate them. + # had to have them so tokenizer could separate them. # multiline strings are handled by do_Text functions if self.lasttext != self.LINESTART \ and self.lasttext != self.LINENUMHOLDER: @@ -1361,7 +1349,7 @@ def __call__(self, toktype, toktext, srow_col, erow_col, line): else: slash = self.raw[oldpos:newpos].find('\\')+oldpos self.out.write(self.raw[oldpos:slash]) - getattr(self, '_send%sText'%(self.markup))(OPERATOR, '\\') + getattr(self, '_send%sText'%(self.markup,))(OPERATOR, '\\') self.linenum+=1 # kludge for line spans in css,xhtml if self.markup in ['XHTML','CSS']: @@ -1374,7 +1362,7 @@ def __call__(self, toktype, toktext, srow_col, erow_col, line): return # Look for operators - if token.LPAR <= toktype and toktype <= token.OP: + if token.LPAR <= toktype <= token.OP: # Trap decorators py2.4 > if toktext == '@': toktype = DECORATOR @@ -1389,7 +1377,7 @@ def __call__(self, toktype, toktext, srow_col, erow_col, line): # Find the end for arguments elif toktext == ':': self.argFlag = 0 - ## Seperate the diffrent operator types + ## Separate the different operator types # Brackets if self.doBrackets and toktext in ['[',']','(',')','{','}']: toktype = BRACKETS @@ -1442,33 +1430,33 @@ def __call__(self, toktype, toktext, srow_col, erow_col, line): elif toktype == token.STRING: text = toktext.lower() # TRIPLE DOUBLE QUOTE's - if (text[:3] == '"""'): + if text[:3] == '"""': toktype = TRIPLEDOUBLEQUOTE - elif (text[:4] == 'r"""'): + elif text[:4] == 'r"""': toktype = TRIPLEDOUBLEQUOTE_R - elif (text[:4] == 'u"""' or - text[:5] == 'ur"""'): + elif ('u"""' == text[:4] or + text[:5] == 'ur"""'): toktype = TRIPLEDOUBLEQUOTE_U # DOUBLE QUOTE's - elif (text[:1] == '"'): + elif text[:1] == '"': toktype = DOUBLEQUOTE - elif (text[:2] == 'r"'): + elif text[:2] == 'r"': toktype = DOUBLEQUOTE_R elif (text[:2] == 'u"' or - text[:3] == 'ur"'): + text[:3] == 'ur"'): toktype = DOUBLEQUOTE_U # TRIPLE SINGLE QUOTE's - elif (text[:3] == "'''"): + elif text[:3] == "'''": toktype = TRIPLESINGLEQUOTE - elif (text[:4] == "r'''"): + elif text[:4] == "r'''": toktype = TRIPLESINGLEQUOTE_R elif (text[:4] == "u'''" or - text[:5] == "ur'''"): + text[:5] == "ur'''"): toktype = TRIPLESINGLEQUOTE_U # SINGLE QUOTE's - elif (text[:1] == "'"): + elif text[:1] == "'": toktype = SINGLEQUOTE - elif (text[:2] == "r'"): + elif text[:2] == "r'": toktype = SINGLEQUOTE_R elif (text[:2] == "u'" or text[:3] == "ur'"): @@ -1578,7 +1566,7 @@ def __call__(self, toktype, toktext, srow_col, erow_col, line): toktext = escape(toktext) # Send text for any markup - getattr(self, '_send%sText'%(self.markup))(toktype, toktext) + getattr(self, '_send%sText'%(self.markup,))(toktype, toktext) return ################################################################# Helpers @@ -1602,7 +1590,7 @@ def _getFile(self, filepath): _file = open(filepath,'r') content = _file.read() _file.close() - except: + except Exception: traceback.print_exc() content = '' return content @@ -1611,18 +1599,17 @@ def _doPageStart(self): getattr(self, '_do%sStart'%(self.markup))() def _doPageHeader(self): - if self.header != None: - if self.header.find('#$#') != -1 or \ - self.header.find('#$#') != -1 or \ - self.header.find('#%#') != -1: + if self.header is not None: + if ('#$#' in self.header or '#@#' in self.header + or '#%' in self.header): self.out.write(self.header[3:]) else: if self.header != '': self.header = self._getFile(self.header) - getattr(self, '_do%sHeader'%(self.markup))() + getattr(self, '_do%sHeader'%(self.markup,))() def _doPageFooter(self): - if self.footer != None: + if self.footer is not None: if self.footer.find('#$#') != -1 or \ self.footer.find('#@#') != -1 or \ self.footer.find('#%#') != -1: @@ -1630,7 +1617,7 @@ def _doPageFooter(self): else: if self.footer != '': self.footer = self._getFile(self.footer) - getattr(self, '_do%sFooter'%(self.markup))() + getattr(self, '_do%sFooter'%(self.markup,))() def _doPageEnd(self): getattr(self, '_do%sEnd'%(self.markup))() @@ -1680,7 +1667,7 @@ def _doHTMLStart(self): # Start of html page self.out.write('\n') - self.out.write('%s\n'%(self.title)) + self.out.write('%s\n'%(self.title,)) self.out.write(self._getDocumentCreatedBy()) self.out.write('\n') @@ -1737,8 +1724,7 @@ def _sendHTMLText(self, toktype, toktext): splittext = toktext.split(self.LINENUMHOLDER) else: splittext = toktext.split(self.LINENUMHOLDER+' ') - store = [] - store.append(splittext.pop(0)) + store = [splittext.pop(0)] lstarttag, lendtag, lcolor = self._getHTMLStyles(LINENUMBER, toktext) count = len(splittext) for item in splittext: @@ -1859,7 +1845,7 @@ def _getCSSStyle(self, key): if seperate_sides==0 and border: style.append('border: %s %s;'%(border,size)) else: - if border == None: + if border is None: border = 'solid' if 'v' in tags:# bottom border style.append('border-bottom:%s %s;'%(border,size)) @@ -1879,7 +1865,7 @@ def _getCSSStyle(self, key): # text backcolor if backcolor: style.append('background-color:%s;'%backcolor) - return (self._getMarkupClass(key),' '.join(style)) + return self._getMarkupClass(key), ' '.join(style) def _sendCSSStyle(self, external=0): """ create external and internal style sheets""" @@ -1909,7 +1895,7 @@ def _sendCSSStyle(self, external=0): def _doCSSStart(self): # Start of css/html 4.01 page self.out.write('\n') - self.out.write('%s\n'%(self.title)) + self.out.write('%s\n'%(self.title,)) self.out.write(self._getDocumentCreatedBy()) self.out.write('\n') @@ -1948,7 +1934,7 @@ def _sendCSSText(self, toktype, toktext): # lnum text ################################################# newmarkup = MARKUPDICT.get(LINENUMBER, MARKUPDICT[NAME]) - lstartspan = ''%(newmarkup) + lstartspan = ''%(newmarkup,) if toktype == LINENUMBER: splittext = toktext.split(self.LINENUMHOLDER) else: @@ -1986,7 +1972,7 @@ def _sendCSSText(self, toktype, toktext): #handle line numbers if present if self.dolinenums: item = item.replace('', - ''%(markupclass)) + ''%(markupclass,)) else: item = '%s'%(markupclass,item) # add endings for line and string tokens @@ -1999,12 +1985,12 @@ def _sendCSSText(self, toktype, toktext): # Send text if toktype != LINENUMBER: if toktype == TEXT and self.textFlag == 'DIV': - startspan = '
'%(markupclass) + startspan = '
'%(markupclass,) endspan = '
' elif toktype == TEXT and self.textFlag == 'RAW': startspan,endspan = ('','') else: - startspan = ''%(markupclass) + startspan = ''%(markupclass,) endspan = '' self.out.write(''.join([startspan, toktext, endspan])) else: @@ -2046,7 +2032,7 @@ def _doXHTMLStart(self): \n \ \n') - self.out.write('%s\n'%(self.title)) + self.out.write('%s\n'%(self.title,)) self.out.write(self._getDocumentCreatedBy()) self.out.write('\n') diff --git a/paste/util/__init__.py b/paste/util/__init__.py index ea4ff1e2..e9f490b3 100644 --- a/paste/util/__init__.py +++ b/paste/util/__init__.py @@ -2,3 +2,13 @@ Package for miscellaneous routines that do not depend on other parts of Paste """ + + +class NoDefault: + """Sentinel for parameters without default value.""" + + def __repr__(self): + return '' + + +NO_DEFAULT = NoDefault() diff --git a/paste/util/cgitb_hook.py b/paste/util/cgitb_hook.py index 959b31d1..b837c437 100644 --- a/paste/util/cgitb_hook.py +++ b/paste/util/cgitb_hook.py @@ -1,4 +1,4 @@ -"""Hook class from the deprecated cgitb library.""" +"""Hook class from the deprecated cgitb module of the standard library.""" # Copyright © 2001-2023 Python Software Foundation; All Rights Reserved. @@ -29,7 +29,7 @@ def reset(): ''' -__UNDEF__ = [] # a special sentinel object +__UNDEF__ = object() # a special sentinel object def small(text): diff --git a/paste/util/classinstance.py b/paste/util/classinstance.py index 6436a443..82ee8bb5 100644 --- a/paste/util/classinstance.py +++ b/paste/util/classinstance.py @@ -1,7 +1,7 @@ # (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 -class classinstancemethod(object): +class classinstancemethod: """ Acts like a class method when called from a class, like an instance method when called by an instance. The method should @@ -16,7 +16,7 @@ def __init__(self, func): def __get__(self, obj, type=None): return _methodwrapper(self.func, obj=obj, type=type) -class _methodwrapper(object): +class _methodwrapper: def __init__(self, func, obj, type): self.func = func diff --git a/paste/util/datetimeutil.py b/paste/util/datetimeutil.py index 3c6d7d9e..705ad1da 100644 --- a/paste/util/datetimeutil.py +++ b/paste/util/datetimeutil.py @@ -63,7 +63,7 @@ def _number(val): try: return int(val) - except: + except Exception: return None # diff --git a/paste/util/filemixin.py b/paste/util/filemixin.py index b06b0397..c313c682 100644 --- a/paste/util/filemixin.py +++ b/paste/util/filemixin.py @@ -1,7 +1,7 @@ # (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 -class FileMixin(object): +class FileMixin: """ Used to provide auxiliary methods to objects simulating files. diff --git a/paste/util/intset.py b/paste/util/intset.py index 40d5566d..c32d3a2c 100644 --- a/paste/util/intset.py +++ b/paste/util/intset.py @@ -1,4 +1,3 @@ -# -*- coding: iso-8859-15 -*- """Immutable integer set type. Integer set class. @@ -76,7 +75,7 @@ def __repr__(self): # Integer set class # ----------------- -class IntSet(object): +class IntSet: """Integer set class with efficient storage in a RLE format of ranges. Supports minus and plus infinity in the range.""" diff --git a/paste/util/ip4.py b/paste/util/ip4.py index 8c486537..f4176ba6 100644 --- a/paste/util/ip4.py +++ b/paste/util/ip4.py @@ -1,4 +1,3 @@ -# -*- coding: iso-8859-15 -*- """IP4 address range set implementation. Implements an IPv4-range type. diff --git a/paste/util/looper.py b/paste/util/looper.py index b28abc7c..e7650119 100644 --- a/paste/util/looper.py +++ b/paste/util/looper.py @@ -59,7 +59,7 @@ def next(self): return result __next__ = next -class loop_pos(object): +class loop_pos: def __init__(self, seq, pos): self.seq = seq diff --git a/paste/util/template.py b/paste/util/template.py index 25459fdb..ee6b25f3 100644 --- a/paste/util/template.py +++ b/paste/util/template.py @@ -76,7 +76,7 @@ class _TemplateContinue(Exception): class _TemplateBreak(Exception): pass -class Template(object): +class Template: default_namespace = { 'start_braces': '{{', @@ -210,7 +210,7 @@ def _eval(self, code, ns, pos): try: value = eval(code, ns) return value - except: + except Exception: exc_info = sys.exc_info() e = exc_info[1] if getattr(e, 'args'): @@ -224,7 +224,7 @@ def _exec(self, code, ns, pos): __traceback_hide__ = True try: exec(code, ns) - except: + except Exception: exc_info = sys.exc_info() e = exc_info[1] e.args = (self._add_line_info(e.args[0], pos),) @@ -236,7 +236,7 @@ def _repr(self, value, pos): if value is None: return '' value = str(value) - except: + except Exception: exc_info = sys.exc_info() e = exc_info[1] e.args = (self._add_line_info(e.args[0], pos),) @@ -309,7 +309,7 @@ def __repr__(self): ## HTML Templating ############################################################ -class html(object): +class html: def __init__(self, value): self.value = value def __str__(self): diff --git a/paste/util/threadinglocal.py b/paste/util/threadinglocal.py index 06f2643e..f953d762 100644 --- a/paste/util/threadinglocal.py +++ b/paste/util/threadinglocal.py @@ -9,7 +9,7 @@ import threading except ImportError: # No threads, so "thread local" means process-global - class local(object): + class local: pass else: try: @@ -17,7 +17,7 @@ class local(object): except AttributeError: # Added in 2.4, but now we'll have to define it ourselves import thread - class local(object): + class local: def __init__(self): self.__dict__['__objs'] = {} diff --git a/paste/wsgilib.py b/paste/wsgilib.py index a7623272..5af8c961 100644 --- a/paste/wsgilib.py +++ b/paste/wsgilib.py @@ -62,7 +62,7 @@ def __del__(self): "WSGI request. finalization function %s not called" % self.close_func, file=sys.stderr) -class add_start_close(object): +class add_start_close: """ An an iterable that iterates over app_iter, calls start_func before the first item is returned, then calls close_func at the @@ -101,7 +101,7 @@ def __del__(self): "WSGI request. finalization function %s not called" % self.close_func, file=sys.stderr) -class chained_app_iters(object): +class chained_app_iters: """ Chains several app_iters together, also delegating .close() to each @@ -134,7 +134,7 @@ def close(self): try: if hasattr(app_iter, 'close'): app_iter.close() - except: + except Exception: got_exc = sys.exc_info() if got_exc: raise got_exc @@ -146,7 +146,7 @@ def __del__(self): "WSGI request. finalization function %s not called" % self.close_func, file=sys.stderr) -class encode_unicode_app_iter(object): +class encode_unicode_app_iter: """ Encodes an app_iterable's unicode responses as strings """ @@ -182,7 +182,7 @@ def catch_errors(application, environ, start_response, error_callback, """ try: app_iter = application(environ, start_response) - except: + except Exception: error_callback(sys.exc_info()) raise if type(app_iter) in (list, tuple): @@ -193,7 +193,7 @@ def catch_errors(application, environ, start_response, error_callback, else: return _wrap_app_iter(app_iter, error_callback, ok_callback) -class _wrap_app_iter(object): +class _wrap_app_iter: def __init__(self, app_iterable, error_callback, ok_callback): self.app_iterable = app_iterable @@ -213,7 +213,7 @@ def next(self): if self.ok_callback: self.ok_callback() raise - except: + except Exception: self.error_callback(sys.exc_info()) raise __next__ = next @@ -241,7 +241,7 @@ def catch_errors_app(application, environ, start_response, error_callback_app, environ, start_response, app_iter, error_callback_app, ok_callback, catch=catch) -class _wrap_app_iter_app(object): +class _wrap_app_iter_app: def __init__(self, environ, start_response, app_iterable, error_callback_app, ok_callback, catch=Exception): @@ -269,7 +269,7 @@ def next(self): if hasattr(self.app_iterable, 'close'): try: self.app_iterable.close() - except: + except Exception: # @@: Print to wsgi.errors? pass new_app_iterable = self.error_callback_app( @@ -370,7 +370,7 @@ def start_response(status, headers, exc_info=None): return (data['status'], data['headers'], b''.join(output), errors.getvalue()) -class ErrorRaiser(object): +class ErrorRaiser: def flush(self): pass @@ -586,7 +586,7 @@ def replacement(*args, **kw): return new_func(*args, **kw) try: replacement.func_name = new_func.func_name - except: + except Exception: pass return replacement diff --git a/paste/wsgiwrappers.py b/paste/wsgiwrappers.py index 6dc2db6b..a384d701 100644 --- a/paste/wsgiwrappers.py +++ b/paste/wsgiwrappers.py @@ -34,7 +34,7 @@ def _push_object(self, obj): # settings is deprecated: use WSGIResponse.defaults instead settings = DeprecatedSettings(default=dict()) -class environ_getter(object): +class environ_getter: """For delegating an attribute to a key in self.environ.""" # @@: Also __set__? Should setting be allowed? def __init__(self, key, default='', default_factory=None): @@ -55,7 +55,7 @@ def __get__(self, obj, type=None): def __repr__(self): return '' % self.key -class WSGIRequest(object): +class WSGIRequest: """WSGI Request API Object This object represents a WSGI request with a more friendly interface. @@ -287,7 +287,7 @@ def __repr__(self): msg += '\ncookies=%s>' % pf(self.cookies) return msg -class WSGIResponse(object): +class WSGIResponse: """A basic HTTP response with content, headers, and out-bound cookies The class variable ``defaults`` specifies default values for diff --git a/tests/test_config.py b/tests/test_config.py index 939c0171..a4fe1d14 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -22,7 +22,7 @@ def app_with_config(environ, start_response): lines = [line.encode('utf8') for line in lines] return lines -class NestingAppWithConfig(object): +class NestingAppWithConfig: def __init__(self, app): self.app = app diff --git a/tests/test_exceptions/test_formatter.py b/tests/test_exceptions/test_formatter.py index 9c53a9ae..5cef21c1 100644 --- a/tests/test_exceptions/test_formatter.py +++ b/tests/test_exceptions/test_formatter.py @@ -4,7 +4,7 @@ import os import difflib -class Mock(object): +class Mock: def __init__(self, **kw): for name, value in kw.items(): setattr(self, name, value) @@ -63,14 +63,14 @@ def test_excersize(): for f in formats: try: raise_error() - except: + except Exception: format(f) def test_content(): for f in formats: try: raise_error() - except: + except Exception: result = format(f) print(result) assert 'test_object' in result @@ -88,7 +88,7 @@ def test_trim(): for f in formats: try: raise_error() - except: + except Exception: result = format(f, trim_source_paths=[(current, '.')]) assert current not in result assert ('%stest_formatter.py' % os.sep) in result, ValueError(repr(result)) @@ -99,7 +99,7 @@ def test_hide(): for f in formats: try: hide(True, raise_error) - except: + except Exception: result = format(f) print(result) assert 'in hide_inner' not in result @@ -128,7 +128,7 @@ def test_hide_supppressed(): pass_through, 'b', raise_error) - except: + except Exception: results.append(format(f)) else: assert 0 @@ -149,7 +149,7 @@ def test_hide_after(): hide, 'reset', raise_error) - except: + except Exception: result = format(f) assert 'AABB' in result assert 'CCDD' not in result @@ -164,7 +164,7 @@ def test_hide_before(): 'AABB', hide, 'before', raise_error) - except: + except Exception: result = format(f) print(result) assert 'AABB' not in result diff --git a/tests/test_exceptions/test_reporter.py b/tests/test_exceptions/test_reporter.py index 92711dd4..889d9004 100644 --- a/tests/test_exceptions/test_reporter.py +++ b/tests/test_exceptions/test_reporter.py @@ -24,7 +24,7 @@ def test_logger(): show_hidden_frames=False) try: int('a') - except: + except Exception: exc_data = collector.collect_exception(*sys.exc_info()) else: assert 0 @@ -38,7 +38,7 @@ def test_logger(): try: 1 / 0 - except: + except Exception: exc_data = collector.collect_exception(*sys.exc_info()) else: assert 0 diff --git a/tests/test_fixture.py b/tests/test_fixture.py index 0e74fe9a..0ec48466 100644 --- a/tests/test_fixture.py +++ b/tests/test_fixture.py @@ -14,7 +14,7 @@ def test_fixture(): res = app.delete('/') assert (res.request.environ['REQUEST_METHOD'] == 'DELETE') - class FakeDict(object): + class FakeDict: def items(self): return [('a', '10'), ('a', '20')] res = app.post('/params', params=FakeDict()) @@ -47,7 +47,7 @@ def response(environ, start_response): TestApp(response).get('/') def test_params_and_upload_files(): - class PostApp(object): + class PostApp: def __call__(self, environ, start_response): start_response("204 No content", []) self.request = WSGIRequest(environ) diff --git a/tests/test_httpserver.py b/tests/test_httpserver.py index fa33d69e..ed819004 100644 --- a/tests/test_httpserver.py +++ b/tests/test_httpserver.py @@ -5,11 +5,11 @@ from paste.httpserver import LimitedLengthFile, WSGIHandler, serve -class MockServer(object): +class MockServer: server_address = ('127.0.0.1', 80) -class MockSocket(object): +class MockSocket: def makefile(self, mode, bufsize): return io.StringIO() diff --git a/tests/test_recursive.py b/tests/test_recursive.py index 525755cc..ec6a1ccc 100644 --- a/tests/test_recursive.py +++ b/tests/test_recursive.py @@ -15,7 +15,7 @@ def error_docs_app(environ, start_response): else: return simple_app(environ, start_response) -class Middleware(object): +class Middleware: def __init__(self, app, url='/error'): self.app = app self.url = url diff --git a/tests/test_registry.py b/tests/test_registry.py index 9b36fc5f..d388ee25 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -39,7 +39,7 @@ def simpleapp_withregistry_default(environ, start_response): return [body] -class RegistryUsingApp(object): +class RegistryUsingApp: def __init__(self, var, value, raise_exc=False): self.var = var self.value = value @@ -57,7 +57,7 @@ def __call__(self, environ, start_response): body = body.encode('utf8') return [body] -class RegistryUsingIteratorApp(object): +class RegistryUsingIteratorApp: def __init__(self, var, value): self.var = var self.value = value @@ -72,7 +72,7 @@ def __call__(self, environ, start_response): body = body.encode('utf8') return iter([body]) -class RegistryMiddleMan(object): +class RegistryMiddleMan: def __init__(self, app, var, value, depth): self.app = app self.var = var diff --git a/tests/test_wsgiwrappers.py b/tests/test_wsgiwrappers.py index ba09cecd..504d55de 100644 --- a/tests/test_wsgiwrappers.py +++ b/tests/test_wsgiwrappers.py @@ -6,7 +6,7 @@ from paste.wsgiwrappers import WSGIRequest, WSGIResponse from paste.util.field_storage import FieldStorage -class AssertApp(object): +class AssertApp: def __init__(self, assertfunc): self.assertfunc = assertfunc