diff --git a/docs/conf.py b/docs/conf.py index 8e15507989..df117b1e32 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -# # pyramid documentation build configuration file, created by # sphinx-quickstart on Wed Jul 16 13:18:14 2008. # diff --git a/src/pyramid/asset.py b/src/pyramid/asset.py index f5900f443c..bdf90ef5e4 100644 --- a/src/pyramid/asset.py +++ b/src/pyramid/asset.py @@ -26,7 +26,7 @@ def asset_spec_from_abspath(abspath, package): pp = package_path(package) + os.path.sep if abspath.startswith(pp): relpath = abspath[len(pp) :] - return '%s:%s' % ( + return '{}:{}'.format( package_name(package), relpath.replace(os.path.sep, '/'), ) diff --git a/src/pyramid/authentication.py b/src/pyramid/authentication.py index 9120ad03be..89aafdf3c4 100644 --- a/src/pyramid/authentication.py +++ b/src/pyramid/authentication.py @@ -74,7 +74,7 @@ def authenticated_userid(self, request): if self.callback is None: debug and self._log( - 'there was no groupfinder callback; returning %r' % (userid,), + f'there was no groupfinder callback; returning {userid!r}', 'authenticated_userid', request, ) @@ -152,14 +152,14 @@ def effective_principals(self, request): else: groups = self.callback(userid, request) debug and self._log( - 'groupfinder callback returned %r as groups' % (groups,), + f'groupfinder callback returned {groups!r} as groups', 'effective_principals', request, ) if groups is None: # is None! debug and self._log( - 'returning effective principals: %r' % (effective_principals,), + f'returning effective principals: {effective_principals!r}', 'effective_principals', request, ) @@ -170,7 +170,7 @@ def effective_principals(self, request): effective_principals.extend(groups) debug and self._log( - 'returning effective principals: %r' % (effective_principals,), + f'returning effective principals: {effective_principals!r}', 'effective_principals', request, ) @@ -717,7 +717,7 @@ def digest(self): ) def cookie_value(self): - v = '%s%08x%s!' % (self.digest(), int(self.time), quote(self.userid)) + v = f'{self.digest()}{int(self.time):08x}{quote(self.userid)}!' if self.tokens: v += self.tokens + '!' v += self.user_data @@ -1174,9 +1174,9 @@ def remember(self, request, userid, max_age=None, tokens=()): try: token = ascii_(token) except UnicodeEncodeError: - raise ValueError("Invalid token %r" % (token,)) + raise ValueError(f"Invalid token {token!r}") if not (isinstance(token, str) and VALID_TOKEN.match(token)): - raise ValueError("Invalid token %r" % (token,)) + raise ValueError(f"Invalid token {token!r}") new_tokens.append(token) tokens = tuple(new_tokens) diff --git a/src/pyramid/config/__init__.py b/src/pyramid/config/__init__.py index c500c53f6f..a49c15cbad 100644 --- a/src/pyramid/config/__init__.py +++ b/src/pyramid/config/__init__.py @@ -447,7 +447,7 @@ def _make_spec(self, path_or_spec): package, filename = resolve_asset_spec(path_or_spec, self.package_name) if package is None: return filename # absolute filename - return '%s:%s' % (package, filename) + return f'{package}:{filename}' def _fix_registry(self): """Fix up a ZCA component registry that is not a diff --git a/src/pyramid/config/actions.py b/src/pyramid/config/actions.py index d80f840ac8..5088bd89a7 100644 --- a/src/pyramid/config/actions.py +++ b/src/pyramid/config/actions.py @@ -537,7 +537,7 @@ def __init__(self, file, line, function, src): def __str__(self): srclines = self.src.split('\n') src = '\n'.join(' %s' % x for x in srclines) - return 'Line %s of file %s:\n%s' % (self.line, self.file, src) + return f'Line {self.line} of file {self.file}:\n{src}' def action_method(wrapped): diff --git a/src/pyramid/config/assets.py b/src/pyramid/config/assets.py index d62b04e571..6f2ddbe4aa 100644 --- a/src/pyramid/config/assets.py +++ b/src/pyramid/config/assets.py @@ -221,7 +221,7 @@ def __init__(self, package, prefix): self.prefix = prefix def get_path(self, resource_name): - return '%s%s' % (self.prefix, resource_name) + return f'{self.prefix}{resource_name}' def get_filename(self, resource_name): path = self.get_path(resource_name) @@ -388,7 +388,7 @@ def register(): intr = self.introspectable( 'asset overrides', (package, override_package, path, override_prefix), - '%s -> %s' % (to_override, override_with), + f'{to_override} -> {override_with}', 'asset override', ) intr['to_override'] = to_override diff --git a/src/pyramid/config/predicates.py b/src/pyramid/config/predicates.py index b49bc513c4..db5df0347e 100644 --- a/src/pyramid/config/predicates.py +++ b/src/pyramid/config/predicates.py @@ -27,7 +27,7 @@ def _add_predicate( intr = self.introspectable( '%s predicates' % type, discriminator, - '%s predicate named %s' % (type, name), + f'{type} predicate named {name}', '%s predicate' % type, ) intr['name'] = name diff --git a/src/pyramid/config/routes.py b/src/pyramid/config/routes.py index 59bc368fe3..a7ff66a475 100644 --- a/src/pyramid/config/routes.py +++ b/src/pyramid/config/routes.py @@ -401,7 +401,7 @@ def external_url_pregenerator(request, elements, kw): scheme = parsed.scheme else: scheme = request.scheme - kw['_app_url'] = '{}://{}'.format(scheme, parsed.netloc) + kw['_app_url'] = f'{scheme}://{parsed.netloc}' if original_pregenerator: elements, kw = original_pregenerator(request, elements, kw) @@ -423,7 +423,7 @@ def external_url_pregenerator(request, elements, kw): introspectables = [] intr = self.introspectable( - 'routes', name, '%s (pattern: %r)' % (name, pattern), 'route' + 'routes', name, f'{name} (pattern: {pattern!r})', 'route' ) intr['name'] = name intr['pattern'] = pattern diff --git a/src/pyramid/config/tweens.py b/src/pyramid/config/tweens.py index dbd6b14edf..0eeac333e6 100644 --- a/src/pyramid/config/tweens.py +++ b/src/pyramid/config/tweens.py @@ -121,7 +121,7 @@ def _add_tween(self, tween_factory, under=None, over=None, explicit=False): if p is not None: if not is_string_or_iterable(p): raise ConfigurationError( - '"%s" must be a string or iterable, not %s' % (t, p) + f'"{t}" must be a string or iterable, not {p}' ) if over is INGRESS or is_nonstr_iter(over) and INGRESS in over: diff --git a/src/pyramid/config/views.py b/src/pyramid/config/views.py index e75fdd1efa..4f5806df35 100644 --- a/src/pyramid/config/views.py +++ b/src/pyramid/config/views.py @@ -904,7 +904,7 @@ def discrim_func(): discriminator = Deferred(discrim_func) if inspect.isclass(view) and attr: - view_desc = 'method %r of %s' % ( + view_desc = 'method {!r} of {}'.format( attr, self.object_description(view), ) @@ -1160,7 +1160,7 @@ def _check_view_options(self, **kw): for opt in getattr(deriver, 'options', []): kw.pop(opt, None) if kw: - raise ConfigurationError('Unknown view options: %s' % (kw,)) + raise ConfigurationError(f'Unknown view options: {kw}') def _apply_view_derivers(self, info): # These derivers are not really derivers and so have fixed order @@ -2248,7 +2248,7 @@ def add(self, config, name, spec, **extra): # pattern, plus any extras passed to us via add_static_view pattern = "%s*subpath" % name # name already ends with slash if config.route_prefix: - route_name = '__%s/%s' % (config.route_prefix, name) + route_name = f'__{config.route_prefix}/{name}' else: route_name = '__%s' % name config.add_route(route_name, pattern, **extra) @@ -2335,7 +2335,7 @@ def _bust_asset_path(self, request, spec, subpath, kw): rawspec = None if pkg_name is not None: - pathspec = '{}:{}{}'.format(pkg_name, pkg_subpath, subpath) + pathspec = f'{pkg_name}:{pkg_subpath}{subpath}' overrides = registry.queryUtility(IPackageOverrides, name=pkg_name) if overrides is not None: resource_name = posixpath.join(pkg_subpath, subpath) @@ -2343,7 +2343,7 @@ def _bust_asset_path(self, request, spec, subpath, kw): for source, filtered_path in sources: rawspec = source.get_path(filtered_path) if hasattr(source, 'pkg_name'): - rawspec = '{}:{}'.format(source.pkg_name, rawspec) + rawspec = f'{source.pkg_name}:{rawspec}' break else: diff --git a/src/pyramid/csrf.py b/src/pyramid/csrf.py index 0ade5f2d6f..304ce4020b 100644 --- a/src/pyramid/csrf.py +++ b/src/pyramid/csrf.py @@ -360,6 +360,6 @@ def _fail(reason): if not any( is_same_domain(originp.netloc, host) for host in trusted_origins ): - return _fail("{} does not match any trusted origins.".format(origin)) + return _fail(f"{origin} does not match any trusted origins.") return True diff --git a/src/pyramid/encode.py b/src/pyramid/encode.py index b6030ed583..1539405341 100644 --- a/src/pyramid/encode.py +++ b/src/pyramid/encode.py @@ -70,13 +70,13 @@ def urlencode(query, doseq=True, quote_via=quote_plus): if is_nonstr_iter(v): for x in v: x = quote_via(x) - result += '%s%s=%s' % (prefix, k, x) + result += f'{prefix}{k}={x}' prefix = '&' elif v is None: - result += '%s%s=' % (prefix, k) + result += f'{prefix}{k}=' else: v = quote_via(v) - result += '%s%s=%s' % (prefix, k, v) + result += f'{prefix}{k}={v}' prefix = '&' diff --git a/src/pyramid/exceptions.py b/src/pyramid/exceptions.py index a82463498f..16aeb7e4ff 100644 --- a/src/pyramid/exceptions.py +++ b/src/pyramid/exceptions.py @@ -91,7 +91,7 @@ def __init__(self, conflicts): def __str__(self): r = ["Conflicting configuration actions"] for discriminator, infos in self._conflicts.items(): - r.append(" For: %s" % (discriminator,)) + r.append(f" For: {discriminator}") for info in infos: for line in str(info).rstrip().split('\n'): r.append(" " + line) @@ -106,7 +106,7 @@ def __init__(self, etype, evalue, info): self.etype, self.evalue, self.info = etype, evalue, info def __str__(self): - return "%s: %s\n in:\n %s" % (self.etype, self.evalue, self.info) + return f"{self.etype}: {self.evalue}\n in:\n {self.info}" class CyclicDependencyError(Exception): @@ -122,6 +122,6 @@ def __str__(self): for cycle in cycles: dependent = cycle dependees = cycles[cycle] - L.append('%r sorts before %r' % (dependent, dependees)) + L.append(f'{dependent!r} sorts before {dependees!r}') msg = 'Implicit ordering cycle:' + '; '.join(L) return msg diff --git a/src/pyramid/httpexceptions.py b/src/pyramid/httpexceptions.py index 06894f9b47..9d61acd8f8 100644 --- a/src/pyramid/httpexceptions.py +++ b/src/pyramid/httpexceptions.py @@ -227,7 +227,7 @@ def __init__( json_formatter=None, **kw, ): - status = '%s %s' % (self.code, self.title) + status = f'{self.code} {self.title}' Response.__init__(self, status=status, **kw) Exception.__init__(self, detail) self.detail = self.message = detail diff --git a/src/pyramid/i18n.py b/src/pyramid/i18n.py index 7c9ef3b4bf..cded99ca59 100644 --- a/src/pyramid/i18n.py +++ b/src/pyramid/i18n.py @@ -273,7 +273,7 @@ def load(cls, dirname=None, locales=None, domain=DEFAULT_DOMAIN): return cls(fileobj=fp, domain=domain) def __repr__(self): - return '<%s: "%s">' % ( + return '<{}: "{}">'.format( type(self).__name__, self._info.get('project-id-version'), ) diff --git a/src/pyramid/path.py b/src/pyramid/path.py index 3db4bf0ff4..a5b7ad212e 100644 --- a/src/pyramid/path.py +++ b/src/pyramid/path.py @@ -98,7 +98,7 @@ def __init__(self, package=CALLER_PACKAGE): __import__(package) except ImportError: raise ValueError( - 'The dotted name %r cannot be imported' % (package,) + f'The dotted name {package!r} cannot be imported' ) package = sys.modules[package] self.package = package_of(package) @@ -209,7 +209,7 @@ def resolve(self, spec): package_name = getattr(self.package, '__name__', None) if package_name is None: raise ValueError( - 'relative spec %r irresolveable without package' % (spec,) + f'relative spec {spec!r} irresolveable without package' ) return PkgResourcesAssetDescriptor(package_name, path) @@ -300,7 +300,7 @@ def resolve(self, dotted): """ if not isinstance(dotted, str): - raise ValueError('%r is not a string' % (dotted,)) + raise ValueError(f'{dotted!r} is not a string') package = self.package if package is CALLER_PACKAGE: package = caller_package() @@ -338,7 +338,7 @@ def _pkg_resources_style(self, value, package): if value.startswith(('.', ':')): if not package: raise ValueError( - 'relative name %r irresolveable without package' % (value,) + f'relative name {value!r} irresolveable without package' ) if value in ['.', ':']: value = package.__name__ @@ -361,7 +361,7 @@ def _zope_dottedname_style(self, value, package): if value == '.': if module is None: raise ValueError( - 'relative name %r irresolveable without package' % (value,) + f'relative name {value!r} irresolveable without package' ) name = module.split('.') else: @@ -401,7 +401,7 @@ def __init__(self, pkg_name, path): self.path = path def absspec(self): - return '%s:%s' % (self.pkg_name, self.path) + return f'{self.pkg_name}:{self.path}' def abspath(self): return os.path.abspath( diff --git a/src/pyramid/predicates.py b/src/pyramid/predicates.py index fe8bc228c8..c4f11c7984 100644 --- a/src/pyramid/predicates.py +++ b/src/pyramid/predicates.py @@ -52,7 +52,7 @@ def __init__(self, val, config): self.val = val def text(self): - return 'path_info = %s' % (self.orig,) + return f'path_info = {self.orig}' phash = text @@ -81,7 +81,7 @@ def __init__(self, val, config): def text(self): return 'request_param %s' % ','.join( - ['%s=%s' % (x, y) if y else x for x, y in self.reqs] + [f'{x}={y}' if y else x for x, y in self.reqs] ) phash = text @@ -116,7 +116,7 @@ def __init__(self, val, config): def text(self): return 'header %s' % ', '.join( - '%s=%s' % (name, val_str) if val_str else name + f'{name}={val_str}' if val_str else name for name, _, val_str in self.val ) @@ -144,7 +144,7 @@ def __init__(self, values, config): self.values = values def text(self): - return 'accept = %s' % (', '.join(self.values),) + return 'accept = {}'.format(', '.join(self.values)) phash = text @@ -157,7 +157,7 @@ def __init__(self, val, config): self.val = config.maybe_dotted(val) def text(self): - return 'containment = %s' % (self.val,) + return f'containment = {self.val}' phash = text @@ -171,7 +171,7 @@ def __init__(self, val, config): self.val = val def text(self): - return 'request_type = %s' % (self.val,) + return f'request_type = {self.val}' phash = text @@ -187,9 +187,7 @@ def __init__(self, val, config): self.reqs = [(x.strip(), y.strip()) for x, y in reqs] def text(self): - return 'match_param %s' % ','.join( - ['%s=%s' % (x, y) for x, y in self.reqs] - ) + return 'match_param %s' % ','.join([f'{x}={y}' for x, y in self.reqs]) phash = text @@ -266,7 +264,7 @@ def __init__(self, val, config): self.val = ('',) + val def text(self): - return 'physical_path = %s' % (self.val,) + return f'physical_path = {self.val}' phash = text @@ -281,7 +279,7 @@ def __init__(self, val, config): self.val = val def text(self): - return "is_authenticated = %r" % (self.val,) + return f"is_authenticated = {self.val!r}" phash = text diff --git a/src/pyramid/registry.py b/src/pyramid/registry.py index 2d790015a8..971ae786aa 100644 --- a/src/pyramid/registry.py +++ b/src/pyramid/registry.py @@ -239,7 +239,7 @@ def __hash__(self): def __repr__(self): self._assert_resolved() - return '<%s category %r, discriminator %r>' % ( + return '<{} category {!r}, discriminator {!r}>'.format( self.__class__.__name__, self.category_name, self.discriminator, diff --git a/src/pyramid/renderers.py b/src/pyramid/renderers.py index a15909cc04..943fde3460 100644 --- a/src/pyramid/renderers.py +++ b/src/pyramid/renderers.py @@ -287,7 +287,7 @@ def default(obj): (obj_iface,), IJSONAdapter, default=_marker ) if result is _marker: - raise TypeError('%r is not JSON serializable' % (obj,)) + raise TypeError(f'{obj!r} is not JSON serializable') return result(obj, request) return default @@ -387,7 +387,7 @@ def _render(value, system): ) ct = 'application/javascript' - body = '/**/{}({});'.format(callback, val) + body = f'/**/{callback}({val});' response = request.response if response.content_type == response.default_content_type: response.content_type = ct diff --git a/src/pyramid/scripts/prequest.py b/src/pyramid/scripts/prequest.py index 32d9bc250e..ab5e81dfc3 100644 --- a/src/pyramid/scripts/prequest.py +++ b/src/pyramid/scripts/prequest.py @@ -207,7 +207,7 @@ def run(self): if self.args.display_headers: self.out(response.status) for name, value in response.headerlist: - self.out('%s: %s' % (name, value)) + self.out(f'{name}: {value}') if response.charset: self.out(response.ubody) else: diff --git a/src/pyramid/scripts/proutes.py b/src/pyramid/scripts/proutes.py index 64cd377272..9c54c06ccd 100644 --- a/src/pyramid/scripts/proutes.py +++ b/src/pyramid/scripts/proutes.py @@ -42,7 +42,7 @@ def _get_print_format(fmt, max_name, max_pattern, max_view, max_method): for index, col in enumerate(fmt): size = max_map[col] + PAD - print_fmt += '{{%s: <{%s}}} ' % (col, index) + print_fmt += f'{{{{{col}: <{{{index}}}}}}} ' sizes.append(size) return print_fmt.format(*sizes) @@ -103,7 +103,7 @@ def _get_view_module(view_callable): if isinstance(original_view, static_view): if original_view.package_name is not None: - return '%s:%s' % ( + return '{}:{}'.format( original_view.package_name, original_view.docroot, ) @@ -117,7 +117,7 @@ def _get_view_module(view_callable): # for them and remove this logic view_name = str(view_callable) - view_module = '%s.%s' % (view_callable.__module__, view_name) + view_module = f'{view_callable.__module__}.{view_name}' # If pyramid wraps something in wsgiapp or wsgiapp2 decorators # that is currently returned as pyramid.router.decorator, lets @@ -171,7 +171,7 @@ def get_route_data(route, registry): if request_method is not None: if view.get('attr') is not None: view_callable = getattr(view['callable'], view['attr']) - view_module = '%s.%s' % ( + view_module = '{}.{}'.format( _get_view_module(view['callable']), view['attr'], ) diff --git a/src/pyramid/scripts/pserve.py b/src/pyramid/scripts/pserve.py index 1bcf6c543e..0c4782ce59 100644 --- a/src/pyramid/scripts/pserve.py +++ b/src/pyramid/scripts/pserve.py @@ -296,9 +296,7 @@ def wsgiref_server_runner(wsgi_app, global_conf, **kw): # pragma: no cover host = kw.get('host', '0.0.0.0') port = int(kw.get('port', 8080)) server = make_server(host, port, wsgi_app) - print( - 'Starting HTTP server on http://%s:%s' % (host, port), file=sys.stderr - ) + print(f'Starting HTTP server on http://{host}:{port}', file=sys.stderr) server.serve_forever() @@ -423,7 +421,7 @@ def cherrypy_server_runner( ) else: print( - 'serving on %s://%s:%s' % (protocol, host, port), + f'serving on {protocol}://{host}:{port}', file=sys.stderr, ) server.start() diff --git a/src/pyramid/scripts/pshell.py b/src/pyramid/scripts/pshell.py index 36c43cbc02..09baf17363 100644 --- a/src/pyramid/scripts/pshell.py +++ b/src/pyramid/scripts/pshell.py @@ -19,7 +19,7 @@ def main(argv=sys.argv, quiet=False): def python_shell_runner(env, help, interact=interact): cprt = 'Type "help" for more information.' - banner = "Python %s on %s\n%s" % (sys.version, sys.platform, cprt) + banner = f"Python {sys.version} on {sys.platform}\n{cprt}" banner += '\n\n' + help + '\n' interact(banner, local=env) @@ -222,7 +222,7 @@ def show_shells(self): self.out('Available shells:') for name in sorted_names: - self.out(' %s' % (name,)) + self.out(f' {name}') return 0 def find_all_shells(self): diff --git a/src/pyramid/scripts/pviews.py b/src/pyramid/scripts/pviews.py index 2731950b42..f35daad457 100644 --- a/src/pyramid/scripts/pviews.py +++ b/src/pyramid/scripts/pviews.py @@ -199,13 +199,13 @@ def __init__(self, infos, context_iface, root_factory, request): def output_route_attrs(self, attrs, indent): route = attrs['matched_route'] - self.out("%sroute name: %s" % (indent, route.name)) - self.out("%sroute pattern: %s" % (indent, route.pattern)) - self.out("%sroute path: %s" % (indent, route.path)) - self.out("%ssubpath: %s" % (indent, '/'.join(attrs['subpath']))) + self.out(f"{indent}route name: {route.name}") + self.out(f"{indent}route pattern: {route.pattern}") + self.out(f"{indent}route path: {route.path}") + self.out("{}subpath: {}".format(indent, '/'.join(attrs['subpath']))) predicates = ', '.join([p.text() for p in route.predicates]) if predicates != '': - self.out("%sroute predicates (%s)" % (indent, predicates)) + self.out(f"{indent}route predicates ({predicates})") def output_view_info(self, view_wrapper, level=1): indent = " " * level @@ -214,12 +214,12 @@ def output_view_info(self, view_wrapper, level=1): attr = getattr(view_wrapper, '__view_attr__', None) request_attrs = getattr(view_wrapper, '__request_attrs__', {}) if attr is not None: - view_callable = "%s.%s.%s" % (module, name, attr) + view_callable = f"{module}.{name}.{attr}" else: attr = view_wrapper.__class__.__name__ if attr == 'function': attr = name - view_callable = "%s.%s" % (module, attr) + view_callable = f"{module}.{attr}" self.out('') if 'matched_route' in request_attrs: self.out("%sRoute:" % indent) @@ -233,14 +233,14 @@ def output_view_info(self, view_wrapper, level=1): else: self.out("%sView:" % indent) self.out("%s-----" % indent) - self.out("%s%s" % (indent, view_callable)) + self.out(f"{indent}{view_callable}") permission = getattr(view_wrapper, '__permission__', None) if permission is not None: - self.out("%srequired permission = %s" % (indent, permission)) + self.out(f"{indent}required permission = {permission}") predicates = getattr(view_wrapper, '__predicates__', None) if predicates is not None: predicate_text = ', '.join([p.text() for p in predicates]) - self.out("%sview predicates (%s)" % (indent, predicate_text)) + self.out(f"{indent}view predicates ({predicate_text})") def run(self): if not self.args.config_uri or not self.args.url: diff --git a/src/pyramid/security.py b/src/pyramid/security.py index e1de9d9a69..39e35a8986 100644 --- a/src/pyramid/security.py +++ b/src/pyramid/security.py @@ -178,7 +178,7 @@ def __str__(self): return self.msg def __repr__(self): - return '<%s instance at %s with msg %r>' % ( + return '<{} instance at {} with msg {!r}>'.format( self.__class__.__name__, id(self), self.msg, diff --git a/src/pyramid/static.py b/src/pyramid/static.py index 5363c16716..71dd715d7a 100644 --- a/src/pyramid/static.py +++ b/src/pyramid/static.py @@ -138,11 +138,11 @@ def get_resource_name(self, request): # normalize asset spec or fs path into resource_path if self.package_name: # package resource - resource_path = '%s/%s' % (self.docroot.rstrip('/'), path) + resource_path = '{}/{}'.format(self.docroot.rstrip('/'), path) if resource_isdir(self.package_name, resource_path): if not request.path_url.endswith('/'): raise self.add_slash_redirect(request) - resource_path = '%s/%s' % ( + resource_path = '{}/{}'.format( resource_path.rstrip('/'), self.index, ) diff --git a/src/pyramid/traversal.py b/src/pyramid/traversal.py index dadeeda649..00b64bae2f 100644 --- a/src/pyramid/traversal.py +++ b/src/pyramid/traversal.py @@ -82,7 +82,7 @@ def find_resource(resource, path): view_name = D['view_name'] context = D['context'] if view_name: - raise KeyError('%r has no subelement %s' % (context, view_name)) + raise KeyError(f'{context!r} has no subelement {view_name}') return context diff --git a/src/pyramid/url.py b/src/pyramid/url.py index b60bed96d0..6b57ec3bb8 100644 --- a/src/pyramid/url.py +++ b/src/pyramid/url.py @@ -634,7 +634,7 @@ def static_url(self, path, **kw): # /absolute/path it's a relative/path; this means its relative # to the package in which the caller's module is defined. package = caller_package() - path = '%s:%s' % (package.__name__, path) + path = f'{package.__name__}:{path}' try: reg = self.registry @@ -679,7 +679,7 @@ def static_path(self, path, **kw): # /absolute/path it's a relative/path; this means its relative # to the package in which the caller's module is defined. package = caller_package() - path = '%s:%s' % (package.__name__, path) + path = f'{package.__name__}:{path}' kw['_app_url'] = self.script_name return self.static_url(path, **kw) @@ -834,7 +834,7 @@ def static_url(path, request, **kw): # /absolute/path it's a relative/path; this means its relative # to the package in which the caller's module is defined. package = caller_package() - path = '%s:%s' % (package.__name__, path) + path = f'{package.__name__}:{path}' return request.static_url(path, **kw) @@ -853,7 +853,7 @@ def static_path(path, request, **kw): # /absolute/path it's a relative/path; this means its relative # to the package in which the caller's module is defined. package = caller_package() - path = '%s:%s' % (package.__name__, path) + path = f'{package.__name__}:{path}' return request.static_path(path, **kw) diff --git a/src/pyramid/urldispatch.py b/src/pyramid/urldispatch.py index 7aea1146b2..83b29ab4ee 100644 --- a/src/pyramid/urldispatch.py +++ b/src/pyramid/urldispatch.py @@ -162,7 +162,7 @@ def _compile_route(route): else: reg = '[^/]+' gen.append('%%(%s)s' % name) # native - name = '(?P<%s>%s)' % (name, reg) # unicode + name = f'(?P<{name}>{reg})' # unicode rpat.append(name) s = pat.pop() # unicode if s: diff --git a/src/pyramid/util.py b/src/pyramid/util.py index 191768eb35..8d384cc84f 100644 --- a/src/pyramid/util.py +++ b/src/pyramid/util.py @@ -388,17 +388,17 @@ def object_description(object): return 'module %s' % modulename if inspect.ismethod(object): oself = getattr(object, '__self__', None) - return 'method %s of class %s.%s' % ( + return 'method {} of class {}.{}'.format( object.__name__, modulename, oself.__class__.__name__, ) if inspect.isclass(object): - dottedname = '%s.%s' % (modulename, object.__name__) + dottedname = f'{modulename}.{object.__name__}' return 'class %s' % dottedname if inspect.isfunction(object): - dottedname = '%s.%s' % (modulename, object.__name__) + dottedname = f'{modulename}.{object.__name__}' return 'function %s' % dottedname return 'object %s' % str(object) diff --git a/src/pyramid/viewderivers.py b/src/pyramid/viewderivers.py index 6461c4829f..64b973e044 100644 --- a/src/pyramid/viewderivers.py +++ b/src/pyramid/viewderivers.py @@ -62,7 +62,7 @@ def map_class(self, view): mapped_view = self.map_class_requestonly(view) else: mapped_view = self.map_class_native(view) - mapped_view.__text__ = 'method %s of %s' % ( + mapped_view.__text__ = 'method {} of {}'.format( self.attr or '__call__', object_description(view), ) @@ -92,7 +92,7 @@ def mapped_view(context, request): return _mapped_view(context, request) if self.attr is not None: - mapped_view.__text__ = 'attr %s of %s' % ( + mapped_view.__text__ = 'attr {} of {}'.format( self.attr, object_description(view), ) diff --git a/tests/pkgs/eventonly/__init__.py b/tests/pkgs/eventonly/__init__.py index d0d4dafb9b..e45a5691f3 100644 --- a/tests/pkgs/eventonly/__init__.py +++ b/tests/pkgs/eventonly/__init__.py @@ -7,7 +7,7 @@ def __init__(self, val, config): self.val = val def text(self): - return 'path_startswith = %s' % (self.val,) + return f'path_startswith = {self.val}' phash = text diff --git a/tests/pkgs/subrequestapp/__init__.py b/tests/pkgs/subrequestapp/__init__.py index 177f5637b5..9c0d0daa13 100644 --- a/tests/pkgs/subrequestapp/__init__.py +++ b/tests/pkgs/subrequestapp/__init__.py @@ -10,7 +10,7 @@ def view_one(request): def view_two(request): # check that request.foo is valid for a subrequest - return 'This came from view_two, foo=%s' % (request.foo,) + return f'This came from view_two, foo={request.foo}' def view_three(request): diff --git a/tests/test_authentication.py b/tests/test_authentication.py index 5f46e4cd14..a950774c5f 100644 --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -1946,7 +1946,7 @@ def cookie_value(self): if isinstance(v, bytes): v = text_(v) new_items.append((k, v)) - result = '/'.join(['%s=%s' % (k, v) for k, v in new_items]) + result = '/'.join([f'{k}={v}' for k, v in new_items]) return result self.AuthTicket = AuthTicket diff --git a/tests/test_config/test_views.py b/tests/test_config/test_views.py index 72f8f01457..c7d8c2721d 100644 --- a/tests/test_config/test_views.py +++ b/tests/test_config/test_views.py @@ -4399,7 +4399,7 @@ def assert_similar_datetime(one, two): one_attr = getattr(one, attr) two_attr = getattr(two, attr) if not one_attr == two_attr: # pragma: no cover - raise AssertionError('%r != %r in %s' % (one_attr, two_attr, attr)) + raise AssertionError(f'{one_attr!r} != {two_attr!r} in {attr}') class DummyStaticURLInfo: diff --git a/tests/test_csrf.py b/tests/test_csrf.py index 191b0864f3..dc1f97829f 100644 --- a/tests/test_csrf.py +++ b/tests/test_csrf.py @@ -128,7 +128,7 @@ def test_get_cookie_csrf_with_no_existing_cookie_sets_cookies(self): [ ( 'Set-Cookie', - 'csrf_token={}; Path=/; SameSite=Lax'.format(token), + f'csrf_token={token}; Path=/; SameSite=Lax', ) ], ) @@ -142,7 +142,7 @@ def test_get_cookie_csrf_nondefault_samesite(self): request.response_callback(request, response) self.assertEqual( response.headerlist, - [('Set-Cookie', 'csrf_token={}; Path=/'.format(token))], + [('Set-Cookie', f'csrf_token={token}; Path=/')], ) def test_existing_cookie_csrf_does_not_set_cookie(self): @@ -169,7 +169,7 @@ def test_new_cookie_csrf_with_existing_cookie_sets_cookies(self): [ ( 'Set-Cookie', - 'csrf_token={}; Path=/; SameSite=Lax'.format(token), + f'csrf_token={token}; Path=/; SameSite=Lax', ) ], ) diff --git a/tests/test_integration.py b/tests/test_integration.py index f671b7c0b9..0b55872d24 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -447,7 +447,7 @@ class TestForbiddenAppHasResult(IntegrationBase, unittest.TestCase): def test_it(self): res = self.testapp.get('/x', status=403) - message, result = [x.strip() for x in res.body.split(b'\n')] + message, result = (x.strip() for x in res.body.split(b'\n')) self.assertTrue(message.endswith(b'failed permission check')) self.assertTrue( result.startswith( diff --git a/tests/test_path.py b/tests/test_path.py index 479e12e407..6f12303f73 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -339,27 +339,33 @@ def test_abspath(self): def test_stream(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() - inst.pkg_resources.resource_stream = lambda x, y: '%s:%s' % (x, y) + inst.pkg_resources.resource_stream = lambda x, y: f'{x}:{y}' s = inst.stream() - self.assertEqual(s, '%s:%s' % ('tests', 'test_asset.py')) + self.assertEqual(s, '{}:{}'.format('tests', 'test_asset.py')) def test_isdir(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() - inst.pkg_resources.resource_isdir = lambda x, y: '%s:%s' % (x, y) - self.assertEqual(inst.isdir(), '%s:%s' % ('tests', 'test_asset.py')) + inst.pkg_resources.resource_isdir = lambda x, y: f'{x}:{y}' + self.assertEqual( + inst.isdir(), '{}:{}'.format('tests', 'test_asset.py') + ) def test_listdir(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() - inst.pkg_resources.resource_listdir = lambda x, y: '%s:%s' % (x, y) - self.assertEqual(inst.listdir(), '%s:%s' % ('tests', 'test_asset.py')) + inst.pkg_resources.resource_listdir = lambda x, y: f'{x}:{y}' + self.assertEqual( + inst.listdir(), '{}:{}'.format('tests', 'test_asset.py') + ) def test_exists(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() - inst.pkg_resources.resource_exists = lambda x, y: '%s:%s' % (x, y) - self.assertEqual(inst.exists(), '%s:%s' % ('tests', 'test_asset.py')) + inst.pkg_resources.resource_exists = lambda x, y: f'{x}:{y}' + self.assertEqual( + inst.exists(), '{}:{}'.format('tests', 'test_asset.py') + ) class TestFSAssetDescriptor(unittest.TestCase): diff --git a/tests/test_response.py b/tests/test_response.py index abfbbc4f11..63def12128 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -33,7 +33,7 @@ def _makeOne(self, file, **kw): def _getPath(self, suffix='txt'): here = os.path.dirname(__file__) - return os.path.join(here, 'fixtures', 'minimal.%s' % (suffix,)) + return os.path.join(here, 'fixtures', f'minimal.{suffix}') def test_with_image_content_type(self): path = self._getPath('jpg') diff --git a/tests/test_scripts/test_proutes.py b/tests/test_scripts/test_proutes.py index 8ac5d0fd11..c0aeb01d39 100644 --- a/tests/test_scripts/test_proutes.py +++ b/tests/test_scripts/test_proutes.py @@ -320,7 +320,7 @@ class IMyRoute(Interface): compare_to = L[-1].split()[:3] view_module = 'tests.test_scripts.dummy' view_str = '' % ( + return ''.format( self.__name__, id(self), ) diff --git a/tests/test_viewderivers.py b/tests/test_viewderivers.py index bec0164618..9baa97c4c0 100644 --- a/tests/test_viewderivers.py +++ b/tests/test_viewderivers.py @@ -2106,4 +2106,4 @@ def assert_similar_datetime(one, two): one_attr = getattr(one, attr) two_attr = getattr(two, attr) if not one_attr == two_attr: # pragma: no cover - raise AssertionError('%r != %r in %s' % (one_attr, two_attr, attr)) + raise AssertionError(f'{one_attr!r} != {two_attr!r} in {attr}')