Skip to content

Commit 8fad04f

Browse files
authored
Merge pull request #57 from edx/jenkins/cleanup-python-code-1d91fc7
Python Code Cleanup
2 parents 1d91fc7 + aea6ee8 commit 8fad04f

31 files changed

Lines changed: 240 additions & 285 deletions

.travis.yml

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@
33
language: python
44

55
python:
6-
- 3.5
7-
- 3.8
8-
6+
- '3.8'
97
env:
10-
- TOXENV=django22
118
- TOXENV=quality
129
- TOXENV=docs
13-
10+
- TOXENV=django22
11+
- TOXENV=django30
12+
- TOXENV=django31
1413
cache:
1514
- pip
1615

@@ -35,7 +34,7 @@ deploy:
3534
distributions: sdist bdist_wheel
3635
on:
3736
tags: true
38-
python: 3.5
39-
condition: '$TOXENV = quality'
37+
python: 3.8
38+
condition: $TOXENV = quality
4039
password:
4140
secure: Q+rwwfNHu5nHSowWdT2K0pDr7pwccsFlTHvwXMUaSK7D7tXRYju9fHWGA3zVHJzYxD8V2UvSYapAdQldkwws5jcspZsDK8wyGS8W66lQ/W/5SnEo/u4+G4OAcSJAb7WIv1K9qI15xqQ+o25sh3kZa+8DSX9Aot+jLkm1vuxv8Togj8MGmdxhBnajlonfaTuK6asAkqvKbJqStcMgv10Vy3Yq2vqYLAqgS4aVpruLLb7F+BA0gY/FGgZNXTtFH/X6EX8L7IZIocp3eQylFq9yeQlGS9nIkTagYbBZcmN0khgJoqRksfuTDsleEsJ8kEKnOo56HjuNByljN/Fh5jpQDb7j2IqocwwarKGz7rDdEH28KN/r/GgUIDquuMLxNvqGTjpLeTjAYlHM1GRbOYlqgCMbWpl7/lcawHkSvkYW47gHl6YqmtI4KX/Nm+/SAWZvxjG0sDY5vUtqmLzH7L6FmAMn0C46H5o+MJ9ChdjRnRDU7BJFrXhKerKOwT1jdk7Dj99Uf39mSkLVsE3RC7+8xDCbBY3+qxmD0XsD6uX4CFfmOQrJEoeDlLbTIkQg8vFetEBedRaBrVbBztnWG9wgAWQYA0oxo+s/67BOTd/UkQrReNTwTaMIwuTaibDEl0OEa7jBtkBAbUKJWg+6Ih0HT0J67dULrswPoZ1V8UHVMsQ=

code_annotations/base.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from code_annotations.helpers import VerboseEcho
1616

1717

18-
class AnnotationConfig(object):
18+
class AnnotationConfig:
1919
"""
2020
Configuration shared among all Code Annotations commands.
2121
"""
@@ -51,10 +51,10 @@ def __init__(self, config_file_path, report_path_override=None, verbosity=1, sou
5151
self.echo.set_verbosity(verbosity)
5252

5353
self.report_path = report_path_override if report_path_override else raw_config['report_path']
54-
self.echo("Configured for report path: {}".format(self.report_path))
54+
self.echo(f"Configured for report path: {self.report_path}")
5555

5656
self.source_path = source_path_override if source_path_override else raw_config['source_path']
57-
self.echo("Configured for source path: {}".format(self.source_path))
57+
self.echo(f"Configured for source path: {self.source_path}")
5858

5959
self._configure_coverage(raw_config.get('coverage_target', None))
6060
self.report_template_dir = raw_config.get('report_template_dir')
@@ -125,7 +125,7 @@ def _is_annotation_token(self, token_or_group):
125125

126126
def _add_annotation_token(self, token):
127127
if token in self.annotation_tokens:
128-
raise ConfigurationException('{} is configured more than once, tokens must be unique.'.format(token))
128+
raise ConfigurationException(f'{token} is configured more than once, tokens must be unique.')
129129
self.annotation_tokens.append(token)
130130

131131
def _configure_coverage(self, coverage_target):
@@ -141,14 +141,14 @@ def _configure_coverage(self, coverage_target):
141141
if coverage_target:
142142
try:
143143
self.coverage_target = float(coverage_target)
144-
except (TypeError, ValueError):
144+
except (TypeError, ValueError) as error:
145145
raise ConfigurationException(
146-
'Coverage target must be a number between 0 and 100 not "{}".'.format(coverage_target)
147-
)
146+
f'Coverage target must be a number between 0 and 100 not "{coverage_target}".'
147+
) from error
148148

149149
if self.coverage_target < 0.0 or self.coverage_target > 100.0:
150150
raise ConfigurationException(
151-
'Invalid coverage target. {} is not between 0 and 100.'.format(self.coverage_target)
151+
f'Invalid coverage target. {self.coverage_target} is not between 0 and 100.'
152152
)
153153
else:
154154
self.coverage_target = None
@@ -167,7 +167,7 @@ def _configure_group(self, group_name, group):
167167
self.groups[group_name] = []
168168

169169
if not group or len(group) == 1:
170-
raise ConfigurationException('Group "{}" must have more than one annotation.'.format(group_name))
170+
raise ConfigurationException(f'Group "{group_name}" must have more than one annotation.')
171171

172172
for annotation in group:
173173
for annotation_token in annotation:
@@ -179,7 +179,7 @@ def _configure_group(self, group_name, group):
179179

180180
# Otherwise it should be a text type, if not then error out
181181
elif not self._is_annotation_token(annotation_value):
182-
raise ConfigurationException('{} is an unknown annotation type.'.format(annotation))
182+
raise ConfigurationException(f'{annotation} is an unknown annotation type.')
183183

184184
self.groups[group_name].append(annotation_token)
185185
self._add_annotation_token(annotation_token)
@@ -219,15 +219,15 @@ def _configure_annotations(self, raw_config):
219219

220220
elif not self._is_annotation_token(annotation): # pragma: no cover
221221
raise TypeError(
222-
'{} is an unknown type, must be strings or lists.'.format(annotation_token_or_group_name)
222+
f'{annotation_token_or_group_name} is an unknown type, must be strings or lists.'
223223
)
224224
else:
225225
self._add_annotation_token(annotation_token_or_group_name)
226226
self.annotation_regexes.append(re.escape(annotation_token_or_group_name))
227227

228-
self.echo.echo_v("Groups configured: {}".format(self.groups))
229-
self.echo.echo_v("Choices configured: {}".format(self.choices))
230-
self.echo.echo_v("Annotation tokens configured: {}".format(self.annotation_tokens))
228+
self.echo.echo_v(f"Groups configured: {self.groups}")
229+
self.echo.echo_v(f"Choices configured: {self.choices}")
230+
self.echo.echo_v(f"Annotation tokens configured: {self.annotation_tokens}")
231231

232232
def _plugin_load_failed_handler(self, *args, **kwargs):
233233
"""
@@ -281,7 +281,7 @@ def _configure_extensions(self):
281281
))
282282

283283

284-
class BaseSearch(object, metaclass=ABCMeta):
284+
class BaseSearch(metaclass=ABCMeta):
285285
"""
286286
Base class for searchers.
287287
"""
@@ -365,7 +365,7 @@ def _check_results_choices(self, annotation):
365365
)
366366
)
367367
elif choice in found_valid_choices:
368-
self._add_annotation_error(annotation, '"{}" is already present in this annotation.'.format(choice))
368+
self._add_annotation_error(annotation, f'"{choice}" is already present in this annotation.')
369369
else:
370370
found_valid_choices.append(choice)
371371
else:
@@ -446,7 +446,7 @@ def check_results(self, all_results):
446446
elif token in found_group_members:
447447
self._add_annotation_error(
448448
annotation,
449-
'"{}" is already in the group that starts with "{}"'.format(token, current_group)
449+
f'"{token}" is already in the group that starts with "{current_group}"'
450450
)
451451
current_group = None
452452
found_group_members = []
@@ -465,7 +465,7 @@ def check_results(self, all_results):
465465
# If we get here there is a problem with check_results' group_children not matching up with
466466
# our config's groups. That puts us in an unknown state, so we should quit.
467467
raise Exception(
468-
'group_children is out of sync with config.groups. {} is not in a group!'.format(token)
468+
f'group_children is out of sync with config.groups. {token} is not in a group!'
469469
)
470470

471471
found_group_members = [token]
@@ -480,7 +480,7 @@ def check_results(self, all_results):
480480
found_group_members = []
481481

482482
if current_group:
483-
self.errors.append('File("{}") finished with an incomplete group {}!'.format(filename, current_group))
483+
self.errors.append(f'File("{filename}") finished with an incomplete group {current_group}!')
484484

485485
return not self.errors
486486

@@ -531,15 +531,15 @@ def _format_results_for_report(self, all_results):
531531
current_group_id = 0
532532

533533
for filename in all_results:
534-
self.echo.echo_vv("report_format: formatting {}".format(filename))
534+
self.echo.echo_vv(f"report_format: formatting {filename}")
535535
formatted_results[filename] = []
536536
current_group = None
537537

538538
found_group_members = []
539539

540540
for annotation in all_results[filename]:
541541
token = annotation['annotation_token']
542-
self.echo.echo_vvv("report_format: formatting annotation token {}".format(token))
542+
self.echo.echo_vvv(f"report_format: formatting annotation token {token}")
543543

544544
if current_group:
545545
if token not in self.config.groups[current_group]:
@@ -572,7 +572,7 @@ def _format_results_for_report(self, all_results):
572572
current_group_id, current_group, token, annotation['line_number'])
573573
)
574574
else:
575-
self.echo.echo_vv('Adding single token {}.'.format(token))
575+
self.echo.echo_vv(f'Adding single token {token}.')
576576
formatted_results[filename].append(annotation)
577577

578578
# If we have all members, this group is done
@@ -603,7 +603,7 @@ def report(self, all_results, report_prefix=''):
603603

604604
formatted_results = self._format_results_for_report(all_results)
605605

606-
self.echo("Generating report to {}".format(report_filename))
606+
self.echo(f"Generating report to {report_filename}")
607607

608608
try:
609609
os.makedirs(self.config.report_path)

code_annotations/cli.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,15 +159,15 @@ def static_find_annotations(config_file, source_path, report_path, verbosity, li
159159
if report:
160160
click.echo("Writing report...")
161161
report_filename = searcher.report(all_results)
162-
click.echo("Report written to {}.".format(report_filename))
162+
click.echo(f"Report written to {report_filename}.")
163163

164164
elapsed = datetime.datetime.now() - start_time
165165
annotation_count = 0
166166

167167
for filename in all_results:
168168
annotation_count += len(all_results[filename])
169169

170-
click.echo("Search found {} annotations in {}.".format(annotation_count, elapsed))
170+
click.echo(f"Search found {annotation_count} annotations in {elapsed}.")
171171

172172
except Exception as exc: # pylint: disable=broad-except
173173
click.echo(traceback.print_exc())
@@ -203,15 +203,15 @@ def generate_docs(
203203
'rendered_report_source_link_prefix'
204204
):
205205
if not getattr(config, key):
206-
raise ConfigurationException("No {key} key in {config_file}".format(key=key, config_file=config_file))
206+
raise ConfigurationException(f"No {key} key in {config_file}")
207207

208208
config.echo("Rendering the following reports: \n{}".format("\n".join([r.name for r in report_files])))
209209

210210
renderer = ReportRenderer(config, report_files)
211211
renderer.render()
212212

213213
elapsed = datetime.datetime.now() - start_time
214-
click.echo("Report rendered in {} seconds.".format(elapsed.total_seconds()))
214+
click.echo(f"Report rendered in {elapsed.total_seconds()} seconds.")
215215
except Exception as exc: # pylint: disable=broad-except
216216
click.echo(traceback.print_exc())
217217
fail(str(exc))

code_annotations/contrib/sphinx/extensions/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,5 @@ def quote_value(value):
5050
except ValueError:
5151
pass
5252
if isinstance(value, str):
53-
return '"{}"'.format(value)
53+
return f'"{value}"'
5454
return str(value)

code_annotations/contrib/sphinx/extensions/featuretoggles.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import os
55

66
import pkg_resources
7-
87
from docutils import nodes
98
from sphinx.util.docutils import SphinxDirective
109

@@ -76,7 +75,7 @@ def iter_nodes(self):
7675
toggle_default_value = toggle.get(".. toggle_default:", "Not defined")
7776
toggle_default_node = nodes.literal(text=quote_value(toggle_default_value))
7877
toggle_section = nodes.section(
79-
"", ids=["featuretoggle-{}".format(toggle_name)]
78+
"", ids=[f"featuretoggle-{toggle_name}"]
8079
)
8180
toggle_section += nodes.title(text=toggle_name)
8281
toggle_section += nodes.paragraph("", "Default: ", toggle_default_node)

code_annotations/contrib/sphinx/extensions/settings.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import os
55

66
import pkg_resources
7-
87
from docutils import nodes
98
from docutils.parsers.rst import directives
109
from sphinx.util.docutils import SphinxDirective
@@ -85,7 +84,7 @@ def iter_nodes(self):
8584
setting_default_node = nodes.literal(
8685
text=quote_value(setting_default_value)
8786
)
88-
setting_section = nodes.section("", ids=["setting-{}".format(setting_name)])
87+
setting_section = nodes.section("", ids=[f"setting-{setting_name}"])
8988
setting_section += nodes.title(text=setting_name)
9089
setting_section += nodes.paragraph("", "Default: ", setting_default_node)
9190
setting_section += nodes.paragraph(

code_annotations/extensions/base.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from code_annotations.helpers import clean_abs_path, clean_annotation, get_annotation_regex
88

99

10-
class AnnotationExtension(object, metaclass=ABCMeta):
10+
class AnnotationExtension(metaclass=ABCMeta):
1111
"""
1212
Abstract base class that annotation extensions will inherit from.
1313
"""
@@ -72,12 +72,11 @@ def __init__(self, config, echo):
7272
config: The configuration dict
7373
echo: VerboseEcho object for logging
7474
"""
75-
super(SimpleRegexAnnotationExtension, self).__init__(config, echo)
75+
super().__init__(config, echo)
7676

7777
if self.lang_comment_definition is None: # pragma: no cover
7878
raise ValueError('Subclasses of SimpleRegexAnnotationExtension must define lang_comment_definition!')
7979

80-
# pylint: disable=not-a-mapping
8180
self.comment_regex = re.compile(
8281
self.comment_regex_fmt.format(**self.lang_comment_definition),
8382
flags=re.VERBOSE
@@ -92,7 +91,7 @@ def __init__(self, config, echo):
9291
# annotation.
9392
self.query = get_annotation_regex(self.config.annotation_regexes)
9493

95-
self.ECHO.echo_v("{} extension regex query: {}".format(self.extension_name, self.query.pattern))
94+
self.ECHO.echo_v(f"{self.extension_name} extension regex query: {self.query.pattern}")
9695

9796
def search(self, file_handle):
9897
"""
@@ -124,13 +123,13 @@ def search(self, file_handle):
124123
try:
125124
annotation_token = inner_match.group('token')
126125
annotation_data = inner_match.group('data')
127-
except IndexError:
126+
except IndexError as error:
128127
# pragma: no cover
129128
raise ValueError('{}::{}: Could not find "data" or "token" groups. Found: {}'.format(
130129
fname,
131130
line,
132131
inner_match.groupdict()
133-
))
132+
)) from error
134133
annotation_token, annotation_data = clean_annotation(annotation_token, annotation_data)
135134
found_annotations.append({
136135
'found_by': self.extension_name,

0 commit comments

Comments
 (0)