Skip to content

Commit

Permalink
Switch to use f-strings.
Browse files Browse the repository at this point in the history
Fixes #841.

I called `pyupgrade --py3-only --py3-plus --py36-plus --py37-plus` on
the Python files.
While looking through the changes, I did some adoptions to sometimes
use f-strings in places where the tool did not use them.

Additionally `pyupgrade` removed some Python 2 compatiblity leftovers.
  • Loading branch information
Michael Howitz committed Jun 30, 2020
1 parent 0045361 commit 4fa3984
Show file tree
Hide file tree
Showing 73 changed files with 184 additions and 197 deletions.
1 change: 0 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
Expand Down
2 changes: 1 addition & 1 deletion docs/zdgbook/examples/PollImplementation.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from Poll import Poll


class PollImplementation(object):
class PollImplementation:
"""
A multiple choice poll, implements the Poll interface.
Expand Down
8 changes: 3 additions & 5 deletions src/App/ApplicationManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def process_time(self, _when=None):
h = h and ('%d hour%s' % (h, (h != 1 and 's' or ''))) or ''
m = m and ('%d min' % m) or ''
s = '%d sec' % s
return '%s %s %s %s' % (d, h, m, s)
return f'{d} {h} {m} {s}'

def sys_version(self):
return sys.version
Expand Down Expand Up @@ -254,8 +254,7 @@ def manage_minimize(self, value=1, REQUEST=None):

if REQUEST is not None:
msg = 'ZODB in-memory caches minimized.'
url = '%s/manage_main?manage_tabs_message=%s' % (REQUEST['URL1'],
msg)
url = f'{REQUEST["URL1"]}/manage_main?manage_tabs_message={msg}'
REQUEST.RESPONSE.redirect(url)

@requestmethod('POST')
Expand All @@ -276,8 +275,7 @@ def manage_pack(self, days=0, REQUEST=None):
msg = 'Invalid days value %s' % str(days)

if REQUEST is not None:
url = '%s/manage_main?manage_tabs_message=%s' % (REQUEST['URL1'],
msg)
url = f'{REQUEST["URL1"]}/manage_main?manage_tabs_message={msg}'
REQUEST['RESPONSE'].redirect(url)

return t
Expand Down
2 changes: 1 addition & 1 deletion src/App/DavLockManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def _findapply(self, obj, result=None, path=''):
addresult = result.append
for id, ob in items:
if path:
p = '%s/%s' % (path, id)
p = f'{path}/{id}'
else:
p = id

Expand Down
4 changes: 2 additions & 2 deletions src/App/Extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _getPath(home, prefix, name, suffixes):

for suffix in suffixes:
if suffix:
fqn = "%s.%s" % (fn, suffix)
fqn = f"{fn}.{suffix}"
else:
fqn = fn
if os.path.exists(fqn):
Expand Down Expand Up @@ -138,7 +138,7 @@ def getPath(prefix, name, checkProduct=1, suffixes=('',), cfg=None):

for suffix in suffixes:
if suffix:
fn = "%s.%s" % (prefix, suffix)
fn = f"{prefix}.{suffix}"
else:
fn = prefix
if os.path.exists(fn):
Expand Down
10 changes: 5 additions & 5 deletions src/App/Management.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def manage_workspace(self, REQUEST):
'You are not authorized to view this object.')

if m.find('/'):
return REQUEST.RESPONSE.redirect("%s/%s" % (REQUEST['URL1'], m))
return REQUEST.RESPONSE.redirect(f"{REQUEST['URL1']}/{m}")

return getattr(self, m)(self, REQUEST)

Expand All @@ -99,11 +99,11 @@ def tabs_path_default(self, REQUEST):
return
last = steps.pop()
for step in steps:
script = '%s/%s' % (script, step)
script = f'{script}/{step}'
yield {'url': linkpat.format(html.escape(script, True)),
'title': html.escape(unquote(step)),
'last': False}
script = '%s/%s' % (script, last)
script = f'{script}/{last}'
yield {'url': linkpat.format(html.escape(script, True)),
'title': html.escape(unquote(last)),
'last': True}
Expand All @@ -127,8 +127,8 @@ def tabs_path_info(self, script, path):
last = path[-1]
del path[-1]
for p in path:
script = "%s/%s" % (script, quote(p))
out.append('<a href="%s/manage_workspace">%s</a>' % (script, p))
script = f"{script}/{quote(p)}"
out.append(f'<a href="{script}/manage_workspace">{p}</a>')
out.append(last)
return '/'.join(out)

Expand Down
2 changes: 1 addition & 1 deletion src/App/ProductContext.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ class __FactoryDispatcher__(FactoryDispatcher):
# 'action': The action in the add drop down in the ZMI. This is
# currently also required by the _verifyObjectPaste
# method of CopyContainers like Folders.
'action': ('manage_addProduct/%s/%s' % (pid, name)),
'action': (f'manage_addProduct/{pid}/{name}'),
# 'product': product id
'product': pid,
# 'permission': Guards the add action.
Expand Down
4 changes: 2 additions & 2 deletions src/App/Undo.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ def undoable_transactions(self, first_transaction=None,
desc = ' '.join(desc[1:])
if len(desc) > 60:
desc = desc[:56] + ' ...'
tid = "%s %s %s %s" % (encode64(tid), t, d1, desc)
tid = f"{encode64(tid)} {t} {d1} {desc}"
else:
tid = "%s %s" % (encode64(tid), t)
tid = f"{encode64(tid)} {t}"
d['id'] = tid

return r
Expand Down
4 changes: 2 additions & 2 deletions src/App/version_txt.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def _prep_version_data():
v = sys.version_info
pyver = "python %d.%d.%d, %s" % (v[0], v[1], v[2], sys.platform)
dist = pkg_resources.get_distribution('Zope')
_version_string = "%s, %s" % (dist.version, pyver)
_version_string = f"{dist.version}, {pyver}"
_zope_version = _parse_version_data(dist.version)


Expand All @@ -72,7 +72,7 @@ def _parse_version_data(version_string):
rel = tuple(int(i) for i in version_dict['release'].split('.'))
micro = rel[2] if len(rel) >= 3 else 0
if version_dict['pre']:
micro = '%s%s' % (micro, version_dict['pre'])
micro = f'{micro}{version_dict["pre"]}'

return ZopeVersion(
rel[0] if len(rel) >= 1 else 0,
Expand Down
10 changes: 4 additions & 6 deletions src/OFS/Application.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def Redirect(self, destination, URL1):
# available as url.
if destination.find('//') >= 0:
raise RedirectException(destination)
raise RedirectException("%s/%s" % (URL1, destination))
raise RedirectException(f"{URL1}/{destination}")

ZopeRedirect = Redirect

Expand Down Expand Up @@ -131,7 +131,7 @@ def __bobo_traverse__(self, REQUEST, name=None):
# Waaa. unrestrictedTraverse calls us with a fake REQUEST.
# There is probably a better fix for this.
try:
REQUEST.RESPONSE.notFoundError("%s\n%s" % (name, method))
REQUEST.RESPONSE.notFoundError(f"{name}\n{method}")
except AttributeError:
raise KeyError(name)

Expand All @@ -149,11 +149,9 @@ def ZopeVersion(self, major=False):
if major:
return zversion.major
else:
version = '%s.%s.%s' % (zversion.major,
zversion.minor,
zversion.micro)
version = f'{zversion.major}.{zversion.minor}.{zversion.micro}'
if zversion.status:
version += '.%s%s' % (zversion.status, zversion.release)
version += f'.{zversion.status}{zversion.release}'

return version

Expand Down
2 changes: 1 addition & 1 deletion src/OFS/CopySupport.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def _get_id(self, id):
while 1:
if self._getOb(id, None) is None:
return id
id = 'copy%s_of_%s' % (n and n + 1 or '', orig_id)
id = 'copy{}_of_{}'.format(n and n + 1 or '', orig_id)
n = n + 1

def _pasteObjects(self, cp, cb_maxsize=0):
Expand Down
2 changes: 1 addition & 1 deletion src/OFS/DTMLDocument.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,6 @@ def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None):
except Exception:
u = REQUEST['URL1']
if submit == "Add and Edit":
u = "%s/%s" % (u, quote(id))
u = f"{u}/{quote(id)}"
REQUEST.RESPONSE.redirect(u + '/manage_main')
return ''
2 changes: 1 addition & 1 deletion src/OFS/DTMLMethod.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,6 @@ def addDTMLMethod(self, id, title='', file='', REQUEST=None, submit=None):
except Exception:
u = REQUEST['URL1']
if submit == "Add and Edit":
u = "%s/%s" % (u, quote(id))
u = f"{u}/{quote(id)}"
REQUEST.RESPONSE.redirect(u + '/manage_main')
return ''
2 changes: 1 addition & 1 deletion src/OFS/FindSupport.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def ZopeFindAndApply(self, obj, obj_ids=None, obj_metatypes=None,

for id, ob in items:
if pre:
p = "%s/%s" % (pre, id)
p = f"{pre}/{id}"
else:
p = id

Expand Down
14 changes: 7 additions & 7 deletions src/OFS/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def _range_request_handler(self, REQUEST, RESPONSE):
)
RESPONSE.setHeader(
'Content-Type',
'multipart/%sbyteranges; boundary=%s' % (
'multipart/{}byteranges; boundary={}'.format(
draftprefix,
boundary,
)
Expand Down Expand Up @@ -975,25 +975,25 @@ def tag(

if alt is None:
alt = getattr(self, 'alt', '')
result = '%s alt="%s"' % (result, html.escape(alt, True))
result = '{} alt="{}"'.format(result, html.escape(alt, True))

if title is None:
title = getattr(self, 'title', '')
result = '%s title="%s"' % (result, html.escape(title, True))
result = '{} title="{}"'.format(result, html.escape(title, True))

if height:
result = '%s height="%s"' % (result, height)
result = f'{result} height="{height}"'

if width:
result = '%s width="%s"' % (result, width)
result = f'{result} width="{width}"'

if css_class is not None:
result = '%s class="%s"' % (result, css_class)
result = f'{result} class="{css_class}"'

for key in list(args.keys()):
value = args.get(key)
if value:
result = '%s %s="%s"' % (result, key, value)
result = f'{result} {key}="{value}"'

return '%s />' % result

Expand Down
2 changes: 1 addition & 1 deletion src/OFS/LockItem.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def getCreator(self):
def getCreatorPath(self):
db, name = self._creator
path = '/'.join(db)
return "/%s/%s" % (path, name)
return f"/{path}/{name}"

@security.public
def getOwner(self):
Expand Down
9 changes: 3 additions & 6 deletions src/OFS/ObjectManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -612,20 +612,17 @@ def manage_exportObject(
if RESPONSE is not None:
RESPONSE.setHeader('Content-type', 'application/data')
RESPONSE.setHeader('Content-Disposition',
'inline;filename=%s.%s' % (id, suffix))
f'inline;filename={id}.{suffix}')
return result

f = os.path.join(CONFIG.clienthome, '%s.%s' % (id, suffix))
f = os.path.join(CONFIG.clienthome, f'{id}.{suffix}')
with open(f, 'w+b') as fd:
ob._p_jar.exportFile(ob._p_oid, fd)

if REQUEST is not None:
return self.manage_main(
self, REQUEST,
manage_tabs_message='"%s" successfully exported to "%s"' % (
id,
f
),
manage_tabs_message=f'"{id}" successfully exported to "{f}"',
title='Object exported'
)

Expand Down
2 changes: 1 addition & 1 deletion src/OFS/PropertySheets.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def __init__(self, id, md=None):

if id in self.__reserved_ids:
raise ValueError(
"'%s' is a reserved Id (forbidden Ids are: %s) " % (
"'{}' is a reserved Id (forbidden Ids are: {}) ".format(
id, self.__reserved_ids))

self.id = id
Expand Down
4 changes: 2 additions & 2 deletions src/OFS/SimpleItem.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def title_and_id(self):
id = id.decode(default_encoding)
if isinstance(title, bytes):
title = title.decode(default_encoding)
return title and ("%s (%s)" % (title, id)) or id
return title and f"{title} ({id})" or id

def this(self):
# Handy way to talk to ourselves in document templates.
Expand Down Expand Up @@ -347,7 +347,7 @@ def title_and_id(self):
If the title is not blank, then the id is included in parens.
"""
t = self.title
return t and ("%s (%s)" % (t, self.__name__)) or self.__name__
return t and f"{t} ({self.__name__})" or self.__name__

def _setId(self, id):
self.__name__ = id
Expand Down
12 changes: 6 additions & 6 deletions src/OFS/absoluteurl.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ def breadcrumbs(self):
raise TypeError(_insufficientContext)

if name:
url = "{}/{}".format(
base[-1]['url'],
quote(name.encode('utf-8'), _safe))
base += ({'name': name,
'url': ("%s/%s" % (base[-1]['url'],
quote(name.encode('utf-8'), _safe)))
}, )

'url': url}, )
return base


Expand Down Expand Up @@ -108,8 +108,8 @@ def breadcrumbs(self):

view = getMultiAdapter((container, request), IAbsoluteURL)
base = tuple(view.breadcrumbs())
base += (
{'name': name, 'url': ("%s/%s" % (base[-1]['url'], name))},)
base += ({'name': name,
'url': "{}/{}".format(base[-1]['url'], name)},)

return base

Expand Down
2 changes: 1 addition & 1 deletion src/OFS/role.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def manage_changePermissions(self, REQUEST):
for role in valid_roles:
role_name = role
role_hash = _string_hash(role_name)
if have("permission_%srole_%s" % (permission_hash, role_hash)):
if have(f"permission_{permission_hash}role_{role_hash}"):
roles.append(role)
name, value = permissions[ip][:2]
try:
Expand Down
2 changes: 1 addition & 1 deletion src/OFS/tests/testApplication.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def test_redirect_not_found(self):
# These are all aliases.
for name in ('Redirect', 'ZopeRedirect'):
response = self.publish(
'/{}?destination=http://google.nl'.format(name))
f'/{name}?destination=http://google.nl')
# This should *not* return a 302 Redirect.
self.assertEqual(response.status, 404)

Expand Down
2 changes: 1 addition & 1 deletion src/OFS/tests/testCopySupportEvents.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def assertEqual(self, first, second, msg=None):
# relied on between objects.
if not set(first) == set(second):
raise self.failureException(
msg or '%r != %r' % (first, second))
msg or f'{first!r} != {second!r}')

def test_1_Clone(self):
# Test clone
Expand Down
2 changes: 1 addition & 1 deletion src/OFS/tests/testRanges.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ def testMultipleRangesBigFileEndOverflow(self):
length = len(self.data)
start, end = length - 100, length + 100
self.expectMultipleRanges(
'3-700,%s-%s' % (start, end),
f'3-700,{start}-{end}',
[(3, 701), (len(self.data) - 100, len(self.data))])

# If-Range headers
Expand Down
6 changes: 3 additions & 3 deletions src/OFS/tests/test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,20 @@ def cb_isCopyable(self):
class NotifyBase(DontComplain):

def manage_afterAdd(self, item, container):
print('old manage_afterAdd %s %s %s' % (
print('old manage_afterAdd {} {} {}'.format(
self.getId(), item.getId(), container.getId()))
super().manage_afterAdd(item, container)

manage_afterAdd.__five_method__ = True # Shut up deprecation warnings

def manage_beforeDelete(self, item, container):
super().manage_beforeDelete(item, container)
print('old manage_beforeDelete %s %s %s' % (
print('old manage_beforeDelete {} {} {}'.format(
self.getId(), item.getId(), container.getId()))
manage_beforeDelete.__five_method__ = True # Shut up deprecation warnings

def manage_afterClone(self, item):
print('old manage_afterClone %s %s' % (self.getId(), item.getId()))
print('old manage_afterClone {} {}'.format(self.getId(), item.getId()))
super().manage_afterClone(item)
manage_afterClone.__five_method__ = True # Shut up deprecation warnings

Expand Down
Loading

0 comments on commit 4fa3984

Please sign in to comment.