Removed redundant numbered parameters from str.format().

Since Python 2.7 and 3.1, "{0} {1}" is equivalent to "{} {}".
This commit is contained in:
Berker Peksag 2014-11-27 02:41:27 +02:00 committed by Tim Graham
parent 50c1d8f24b
commit 560b4207b1
24 changed files with 72 additions and 72 deletions

View File

@ -178,7 +178,7 @@ class AdminReadonlyField(object):
if not self.is_first:
attrs["class"] = "inline"
label = self.field['label']
return format_html('<label{0}>{1}:</label>',
return format_html('<label{}>{}:</label>',
flatatt(attrs),
capfirst(force_text(label)))

View File

@ -34,9 +34,9 @@ def paginator_number(cl, i):
if i == DOT:
return '... '
elif i == cl.page_num:
return format_html('<span class="this-page">{0}</span> ', i + 1)
return format_html('<span class="this-page">{}</span> ', i + 1)
else:
return format_html('<a href="{0}"{1}>{2}</a> ',
return format_html('<a href="{}"{}>{}</a> ',
cl.get_query_string({PAGE_VAR: i}),
mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
i + 1)
@ -117,13 +117,13 @@ def result_headers(cl):
# Not sortable
yield {
"text": text,
"class_attrib": format_html(' class="column-{0}"', field_name),
"class_attrib": format_html(' class="column-{}"', field_name),
"sortable": False,
}
continue
# OK, it is sortable if we got this far
th_classes = ['sortable', 'column-{0}'.format(field_name)]
th_classes = ['sortable', 'column-{}'.format(field_name)]
order_type = ''
new_order_type = 'asc'
sort_priority = 0
@ -168,14 +168,14 @@ def result_headers(cl):
"url_primary": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}),
"url_remove": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}),
"url_toggle": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}),
"class_attrib": format_html(' class="{0}"', ' '.join(th_classes)) if th_classes else '',
"class_attrib": format_html(' class="{}"', ' '.join(th_classes)) if th_classes else '',
}
def _boolean_icon(field_val):
icon_url = static('admin/img/icon-%s.gif' %
{True: 'yes', False: 'no', None: 'unknown'}[field_val])
return format_html('<img src="{0}" alt="{1}" />', icon_url, field_val)
return format_html('<img src="{}" alt="{}" />', icon_url, field_val)
def items_for_result(cl, result, form):
@ -249,15 +249,15 @@ def items_for_result(cl, result, form):
value = result.serializable_value(attr)
result_id = escapejs(value)
link_or_text = format_html(
'<a href="{0}"{1}>{2}</a>',
'<a href="{}"{}>{}</a>',
url,
format_html(
' onclick="opener.dismissRelatedLookupPopup(window, '
'&#39;{0}&#39;); return false;"', result_id
'&#39;{}&#39;); return false;"', result_id
) if cl.is_popup else '',
result_repr)
yield format_html('<{0}{1}>{2}</{3}>',
yield format_html('<{}{}>{}</{}>',
table_tag,
row_class,
link_or_text,
@ -271,9 +271,9 @@ def items_for_result(cl, result, form):
form[cl.model._meta.pk.name].is_hidden)):
bf = form[field_name]
result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
yield format_html('<td{0}>{1}</td>', row_class, result_repr)
yield format_html('<td{}>{}</td>', row_class, result_repr)
if form and not form[cl.model._meta.pk.name].is_hidden:
yield format_html('<td>{0}</td>', force_text(form[cl.model._meta.pk.name]))
yield format_html('<td>{}</td>', force_text(form[cl.model._meta.pk.name]))
class ResultList(list):

View File

@ -142,7 +142,7 @@ def get_deleted_objects(objs, opts, user, admin_site, using):
if not user.has_perm(p):
perms_needed.add(opts.verbose_name)
# Display a link to the admin page.
return format_html('{0}: <a href="{1}">{2}</a>',
return format_html('{}: <a href="{}">{}</a>',
capfirst(opts.verbose_name),
admin_url,
obj)

View File

@ -87,7 +87,7 @@ class AdminSplitDateTime(forms.SplitDateTimeWidget):
forms.MultiWidget.__init__(self, widgets, attrs)
def format_output(self, rendered_widgets):
return format_html('<p class="datetime">{0} {1}<br />{2} {3}</p>',
return format_html('<p class="datetime">{} {}<br />{} {}</p>',
_('Date:'), rendered_widgets[0],
_('Time:'), rendered_widgets[1])
@ -95,9 +95,9 @@ class AdminSplitDateTime(forms.SplitDateTimeWidget):
class AdminRadioFieldRenderer(RadioFieldRenderer):
def render(self):
"""Outputs a <ul> for this set of radio fields."""
return format_html('<ul{0}>\n{1}\n</ul>',
return format_html('<ul{}>\n{}\n</ul>',
flatatt(self.attrs),
format_html_join('\n', '<li>{0}</li>',
format_html_join('\n', '<li>{}</li>',
((force_text(w),) for w in self)))
@ -325,7 +325,7 @@ class AdminURLFieldWidget(forms.URLInput):
value = force_text(self._format_value(value))
final_attrs = {'href': smart_urlquote(value)}
html = format_html(
'<p class="url">{0} <a{1}>{2}</a><br />{3} {4}</p>',
'<p class="url">{} <a{}>{}</a><br />{} {}</p>',
_('Currently:'), flatatt(final_attrs), value,
_('Change:'), html
)

View File

@ -44,12 +44,12 @@ class ReadOnlyPasswordHashWidget(forms.Widget):
"Invalid password format or unknown hashing algorithm."))
else:
summary = format_html_join('',
"<strong>{0}</strong>: {1} ",
"<strong>{}</strong>: {} ",
((ugettext(key), value)
for key, value in hasher.safe_summary(encoded).items())
)
return format_html("<div{0}>{1}</div>", flatatt(final_attrs), summary)
return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
class ReadOnlyPasswordHashField(forms.Field):

View File

@ -121,17 +121,17 @@ class GoogleMap(object):
@property
def body(self):
"Returns HTML body tag for loading and unloading Google Maps javascript."
return format_html('<body {0} {1}>', self.onload, self.onunload)
return format_html('<body {} {}>', self.onload, self.onunload)
@property
def onload(self):
"Returns the `onload` HTML <body> attribute."
return format_html('onload="{0}.{1}_load()"', self.js_module, self.dom_id)
return format_html('onload="{}.{}_load()"', self.js_module, self.dom_id)
@property
def api_script(self):
"Returns the <script> tag for the Google Maps API javascript."
return format_html('<script src="{0}{1}" type="text/javascript"></script>',
return format_html('<script src="{}{}" type="text/javascript"></script>',
self.api_url, self.key)
@property
@ -142,18 +142,18 @@ class GoogleMap(object):
@property
def scripts(self):
"Returns all <script></script> tags required with Google Maps JavaScript."
return format_html('{0}\n <script type="text/javascript">\n//<![CDATA[\n{1}//]]>\n </script>',
return format_html('{}\n <script type="text/javascript">\n//<![CDATA[\n{}//]]>\n </script>',
self.api_script, mark_safe(self.js))
@property
def style(self):
"Returns additional CSS styling needed for Google Maps on IE."
return format_html('<style type="text/css">{0}</style>', self.vml_css)
return format_html('<style type="text/css">{}</style>', self.vml_css)
@property
def xhtml(self):
"Returns XHTML information needed for IE VML overlays."
return format_html('<html xmlns="http://www.w3.org/1999/xhtml" {0}>', self.xmlns)
return format_html('<html xmlns="http://www.w3.org/1999/xhtml" {}>', self.xmlns)
@property
def icons(self):

View File

@ -601,7 +601,7 @@ class SessionMiddlewareTests(unittest.TestCase):
# A deleted cookie header looks like:
# Set-Cookie: sessionid=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/
self.assertEqual(
'Set-Cookie: {0}=; expires=Thu, 01-Jan-1970 00:00:00 GMT; '
'Set-Cookie: {}=; expires=Thu, 01-Jan-1970 00:00:00 GMT; '
'Max-Age=0; Path=/'.format(settings.SESSION_COOKIE_NAME),
str(response.cookies[settings.SESSION_COOKIE_NAME])
)

View File

@ -645,7 +645,7 @@ class BoundField(object):
# Translators: If found as last label character, these punctuation
# characters will prevent the default label_suffix to be appended to the label
if label_suffix and contents and contents[-1] not in _(':?.!'):
contents = format_html('{0}{1}', contents, label_suffix)
contents = format_html('{}{}', contents, label_suffix)
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
if id_:
@ -659,7 +659,7 @@ class BoundField(object):
else:
attrs['class'] = self.form.required_css_class
attrs = flatatt(attrs) if attrs else ''
contents = format_html('<label{0}>{1}</label>', attrs, contents)
contents = format_html('<label{}>{}</label>', attrs, contents)
else:
contents = conditional_escape(contents)
return mark_safe(contents)

View File

@ -39,8 +39,8 @@ def flatatt(attrs):
key_value_attrs.append((attr, value))
return (
format_html_join('', ' {0}="{1}"', sorted(key_value_attrs)) +
format_html_join('', ' {0}', sorted(boolean_attrs))
format_html_join('', ' {}="{}"', sorted(key_value_attrs)) +
format_html_join('', ' {}', sorted(boolean_attrs))
)
@ -61,8 +61,8 @@ class ErrorDict(dict):
if not self:
return ''
return format_html(
'<ul class="errorlist">{0}</ul>',
format_html_join('', '<li>{0}{1}</li>', ((k, force_text(v)) for k, v in self.items()))
'<ul class="errorlist">{}</ul>',
format_html_join('', '<li>{}{}</li>', ((k, force_text(v)) for k, v in self.items()))
)
def as_text(self):
@ -110,9 +110,9 @@ class ErrorList(UserList, list):
return ''
return format_html(
'<ul class="{0}">{1}</ul>',
'<ul class="{}">{}</ul>',
self.error_class,
format_html_join('', '<li>{0}</li>', ((force_text(e),) for e in self))
format_html_join('', '<li>{}</li>', ((force_text(e),) for e in self))
)
def as_text(self):

View File

@ -53,7 +53,7 @@ class Media(object):
def render_js(self):
return [
format_html(
'<script type="text/javascript" src="{0}"></script>',
'<script type="text/javascript" src="{}"></script>',
self.absolute_path(path)
) for path in self._js
]
@ -64,7 +64,7 @@ class Media(object):
media = sorted(self._css.keys())
return chain(*[[
format_html(
'<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />',
'<link href="{}" type="text/css" media="{}" rel="stylesheet" />',
self.absolute_path(path), medium
) for path in self._css[medium]
] for medium in media])
@ -252,7 +252,7 @@ class Input(Widget):
if value != '':
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_text(self._format_value(value))
return format_html('<input{0} />', flatatt(final_attrs))
return format_html('<input{} />', flatatt(final_attrs))
class TextInput(Input):
@ -315,7 +315,7 @@ class MultipleHiddenInput(HiddenInput):
# An ID attribute was given. Add a numeric index as a suffix
# so that the inputs don't all have the same ID attribute.
input_attrs['id'] = '%s_%s' % (id_, i)
inputs.append(format_html('<input{0} />', flatatt(input_attrs)))
inputs.append(format_html('<input{} />', flatatt(input_attrs)))
return mark_safe('\n'.join(inputs))
def value_from_datadict(self, data, files, name):
@ -429,7 +429,7 @@ class Textarea(Widget):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
return format_html('<textarea{0}>\r\n{1}</textarea>',
return format_html('<textarea{}>\r\n{}</textarea>',
flatatt(final_attrs),
force_text(value))
@ -478,7 +478,7 @@ class CheckboxInput(Widget):
if not (value is True or value is False or value is None or value == ''):
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_text(value)
return format_html('<input{0} />', flatatt(final_attrs))
return format_html('<input{} />', flatatt(final_attrs))
def value_from_datadict(self, data, files, name):
if name not in data:
@ -507,7 +507,7 @@ class Select(Widget):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select{0}>', flatatt(final_attrs))]
output = [format_html('<select{}>', flatatt(final_attrs))]
options = self.render_options(choices, [value])
if options:
output.append(options)
@ -525,7 +525,7 @@ class Select(Widget):
selected_choices.remove(option_value)
else:
selected_html = ''
return format_html('<option value="{0}"{1}>{2}</option>',
return format_html('<option value="{}"{}>{}</option>',
option_value,
selected_html,
force_text(option_label))
@ -536,7 +536,7 @@ class Select(Widget):
output = []
for option_value, option_label in chain(self.choices, choices):
if isinstance(option_label, (list, tuple)):
output.append(format_html('<optgroup label="{0}">', force_text(option_value)))
output.append(format_html('<optgroup label="{}">', force_text(option_value)))
for option in option_label:
output.append(self.render_option(selected_choices, *option))
output.append('</optgroup>')
@ -579,7 +579,7 @@ class SelectMultiple(Select):
if value is None:
value = []
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select multiple="multiple"{0}>', flatatt(final_attrs))]
output = [format_html('<select multiple="multiple"{}>', flatatt(final_attrs))]
options = self.render_options(choices, value)
if options:
output.append(options)
@ -615,12 +615,12 @@ class ChoiceInput(SubWidget):
def render(self, name=None, value=None, attrs=None, choices=()):
if self.id_for_label:
label_for = format_html(' for="{0}"', self.id_for_label)
label_for = format_html(' for="{}"', self.id_for_label)
else:
label_for = ''
attrs = dict(self.attrs, **attrs) if attrs else self.attrs
return format_html(
'<label{0}>{1} {2}</label>', label_for, self.tag(attrs), self.choice_label
'<label{}>{} {}</label>', label_for, self.tag(attrs), self.choice_label
)
def is_checked(self):
@ -631,7 +631,7 @@ class ChoiceInput(SubWidget):
final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
return format_html('<input{0} />', flatatt(final_attrs))
return format_html('<input{} />', flatatt(final_attrs))
@property
def id_for_label(self):
@ -693,7 +693,7 @@ class ChoiceFieldRenderer(object):
if isinstance(choice_label, (tuple, list)):
attrs_plus = self.attrs.copy()
if id_:
attrs_plus['id'] += '_{0}'.format(i)
attrs_plus['id'] += '_{}'.format(i)
sub_ul_renderer = ChoiceFieldRenderer(name=self.name,
value=self.value,
attrs=attrs_plus,
@ -707,7 +707,7 @@ class ChoiceFieldRenderer(object):
output.append(format_html(self.inner_html,
choice_value=force_text(w), sub_widgets=''))
return format_html(self.outer_html,
id_attr=format_html(' id="{0}"', id_) if id_ else '',
id_attr=format_html(' id="{}"', id_) if id_ else '',
content=mark_safe('\n'.join(output)))

View File

@ -56,7 +56,7 @@ class CsrfTokenNode(Node):
if csrf_token == 'NOTPROVIDED':
return format_html("")
else:
return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{0}' />", csrf_token)
return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{}' />", csrf_token)
else:
# It's very probable that the token is missing because of
# misconfiguration, so we raise a warning
@ -195,7 +195,7 @@ class ForNode(Node):
# Check loop variable count before unpacking
if num_loopvars != len_item:
warnings.warn(
"Need {0} values to unpack in for loop; got {1}. "
"Need {} values to unpack in for loop; got {}. "
"This will raise an exception in Django 2.0."
.format(num_loopvars, len_item),
RemovedInDjango20Warning)

View File

@ -105,7 +105,7 @@ def format_html_join(sep, format_string, args_generator):
Example:
format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
for u in users))
"""

View File

@ -109,7 +109,7 @@ class AdminEmailHandler(logging.Handler):
record.getMessage()
)
filter = get_exception_reporter_filter(request)
request_repr = '\n{0}'.format(force_text(filter.get_request_repr(request)))
request_repr = '\n{}'.format(force_text(filter.get_request_repr(request)))
except Exception:
subject = '%s: %s' % (
record.levelname,

View File

@ -106,7 +106,7 @@ the assembly and transmission of a large CSV file::
# Generate a sequence of rows. The range is based on the maximum number of
# rows that can be handled by a single sheet in most spreadsheet
# applications.
rows = (["Row {0}".format(idx), str(idx)] for idx in range(65536))
rows = (["Row {}".format(idx), str(idx)] for idx in range(65536))
pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
response = StreamingHttpResponse((writer.writerow(row) for row in rows),

View File

@ -325,7 +325,7 @@ the following ``render`` method after the existing ``__init__`` method::
value = force_text(self._format_value(value))
final_attrs = {'href': mark_safe(smart_urlquote(value))}
html = format_html(
'<p class="url">{0} <a {1}>{2}</a><br />{3} {4}</p>',
'<p class="url">{} <a {}>{}</a><br />{} {}</p>',
_('Currently:'), flatatt(final_attrs), value,
_('Change:'), html
)
@ -443,7 +443,7 @@ This patch file contains all your changes and should look this:
+ value = force_text(self._format_value(value))
+ final_attrs = {'href': mark_safe(smart_urlquote(value))}
+ html = format_html(
+ '<p class="url">{0} <a {1}>{2}</a><br />{3} {4}</p>',
+ '<p class="url">{} <a {}>{}</a><br />{} {}</p>',
+ _('Currently:'), flatatt(final_attrs), value,
+ _('Change:'), html
+ )

View File

@ -590,7 +590,7 @@ subclass::
color_code = models.CharField(max_length=6)
def colored_name(self):
return format_html('<span style="color: #{0};">{1} {2}</span>',
return format_html('<span style="color: #{};">{} {}</span>',
self.color_code,
self.first_name,
self.last_name)
@ -647,7 +647,7 @@ subclass::
color_code = models.CharField(max_length=6)
def colored_first_name(self):
return format_html('<span style="color: #{0};">{1}</span>',
return format_html('<span style="color: #{};">{}</span>',
self.color_code,
self.first_name)
@ -1060,7 +1060,7 @@ subclass::
# line by a linebreak
return format_html_join(
mark_safe('<br/>'),
'{0}',
'{}',
((line,) for line in instance.get_full_address()),
) or "<span class='errors'>I can't determine this address.</span>"

View File

@ -605,7 +605,7 @@ escaping HTML.
You should instead use::
format_html("{0} <b>{1}</b> {2}",
format_html("{} <b>{}</b> {}",
mark_safe(some_html), some_text, some_other_text)
This has the advantage that you don't need to apply :func:`escape` to each
@ -627,7 +627,7 @@ escaping HTML.
``args_generator`` should be an iterator that returns the sequence of
``args`` that will be passed to :func:`format_html`. For example::
format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
for u in users))
.. function:: strip_tags(value)

View File

@ -239,7 +239,7 @@ class FileUploadTests(TestCase):
for name, filename, _ in cases:
payload.write("\r\n".join([
'--' + client.BOUNDARY,
'Content-Disposition: form-data; name="{0}"; filename="{1}"',
'Content-Disposition: form-data; name="{}"; filename="{}"',
'Content-Type: application/octet-stream',
'',
'Oops.',
@ -258,7 +258,7 @@ class FileUploadTests(TestCase):
result = json.loads(response.content.decode('utf-8'))
for name, _, expected in cases:
got = result[name]
self.assertEqual(expected, got, 'Mismatch for {0}'.format(name))
self.assertEqual(expected, got, 'Mismatch for {}'.format(name))
self.assertLess(len(got), 256,
"Got a long file name (%s characters)." % len(got))

View File

@ -1384,7 +1384,7 @@ class FormsTestCase(TestCase):
"""
class CustomWidget(TextInput):
def render(self, name, value, attrs=None):
return format_html(str('<input{0} />'), ' id=custom')
return format_html(str('<input{} />'), ' id=custom')
class SampleForm(Form):
name = CharField(widget=CustomWidget)

View File

@ -316,7 +316,7 @@ class EmptyLabelTestCase(TestCase):
m = f.save()
self.assertEqual(expected, getattr(m, key))
self.assertEqual('No Preference',
getattr(m, 'get_{0}_display'.format(key))())
getattr(m, 'get_{}_display'.format(key))())
def test_empty_field_integer(self):
f = EmptyIntegerLabelChoiceForm()

View File

@ -319,12 +319,12 @@ class TemplateRegressionTests(TestCase):
# When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below.
iter2 = iter([1, 2, 3])
output2 = template.render(Context({'foo': range(3), 'get_value': lambda: next(iter2)}))
self.assertEqual(output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {0}'.format(output2))
self.assertEqual(output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {}'.format(output2))
yield 3
gen1 = gen()
output1 = template.render(Context({'foo': range(3), 'get_value': lambda: next(gen1)}))
self.assertEqual(output1, '[0,1,2,3]', 'Expected [0,1,2,3] in first template, got {0}'.format(output1))
self.assertEqual(output1, '[0,1,2,3]', 'Expected [0,1,2,3] in first template, got {}'.format(output1))
def test_cache_regression_20130(self):
t = Template('{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}')

View File

@ -43,7 +43,7 @@ class TestUtilsHtml(TestCase):
def test_format_html(self):
self.assertEqual(
html.format_html("{0} {1} {third} {fourth}",
html.format_html("{} {} {third} {fourth}",
"< Dangerous >",
html.mark_safe("<b>safe</b>"),
third="< dangerous again",

View File

@ -28,13 +28,13 @@ class TestNumberFormat(TestCase):
self.assertEqual(nformat('-1234.33', '.', decimal_pos=1), '-1234.3')
def test_large_number(self):
most_max = ('{0}179769313486231570814527423731704356798070567525844996'
most_max = ('{}179769313486231570814527423731704356798070567525844996'
'598917476803157260780028538760589558632766878171540458953'
'514382464234321326889464182768467546703537516986049910576'
'551282076245490090389328944075868508455133942304583236903'
'222948165808559332123348274797826204144723168738177180919'
'29988125040402618412485836{1}')
most_max2 = ('{0}35953862697246314162905484746340871359614113505168999'
'29988125040402618412485836{}')
most_max2 = ('{}35953862697246314162905484746340871359614113505168999'
'31978349536063145215600570775211791172655337563430809179'
'07028764928468642653778928365536935093407075033972099821'
'15310256415249098018077865788815173701691026788460916647'

View File

@ -17,7 +17,7 @@ class SafeJoinTests(unittest.TestCase):
drive, path = os.path.splitdrive(safe_join("/", "path"))
self.assertEqual(
path,
"{0}path".format(os.path.sep),
"{}path".format(os.path.sep),
)
drive, path = os.path.splitdrive(safe_join("/", ""))