Skip to content

Commit

Permalink
Use f-strings over string formatting
Browse files Browse the repository at this point in the history
This replaces all string format statements
over f-strings as it is more preferred way
in Python 3.

Closes coala#6150
  • Loading branch information
jkklapp authored and abhishalya committed May 16, 2021
1 parent c294585 commit 52b9d18
Show file tree
Hide file tree
Showing 48 changed files with 259 additions and 282 deletions.
32 changes: 16 additions & 16 deletions coalib/bears/Bear.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,13 +387,13 @@ def run(self, *args, dependency_results=None, **kwargs):
raise NotImplementedError

def _dump_bear_profile_data(self, profiler):
filename = '{}_{}.prof'.format(self.section.name, self.name)
filename = f'{self.section.name}_{self.name}.prof'
path = join(self.profile, filename)
if not isdir(self.profile):
try:
makedirs(self.profile)
except FileExistsError:
logging.error('File exists :'.format(self.profile))
logging.error(f'File exists {self.profile}:')
raise SystemExit(2)

profiler.dump_stats(path)
Expand Down Expand Up @@ -425,8 +425,7 @@ def run_bear_from_section(self, args, kwargs):
kwargs.update(
self.get_metadata().create_params_from_section(self.section))
except ValueError as err:
self.warn('The bear {} cannot be executed.'.format(
self.name), str(err))
self.warn(f'The bear {self.name} cannot be executed.', str(err))
return
if self.debugger:
return debug_run(self.run, Debugger(bear=self), *args, **kwargs)
Expand All @@ -438,7 +437,7 @@ def run_bear_from_section(self, args, kwargs):
def execute(self, *args, debug=False, **kwargs):
name = self.name
try:
self.debug('Running bear {}...'.format(name))
self.debug(f'Running bear {name}...')

# If `dependency_results` kwargs is defined but there are no
# dependency results (usually in Bear that has no dependency)
Expand All @@ -457,28 +456,30 @@ def execute(self, *args, debug=False, **kwargs):
raise

if isinstance(exc, ZeroOffsetError):
self.err('Bear {} violated one-based offset convention.'
.format(name), str(exc))
self.err(
f'Bear {name} violated one-based offset convention.',
str(exc))

if (self.kind() == BEAR_KIND.LOCAL
and ('log_level' not in self.section
or self.section['log_level'].value != 'DEBUG')):
self.err('Bear {} failed to run on file {}. Take a look '
self.err(f'Bear {name} failed to run on file {args[0]}. '
'Take a look '
'at debug messages (`-V`) for further '
'information.'.format(name, args[0]))
'information.')
elif ('log_level' not in self.section
or self.section['log_level'].value != 'DEBUG'):
self.err('Bear {} failed to run. Take a look '
self.err(f'Bear {name} failed to run. Take a look '
'at debug messages (`-V`) for further '
'information.'.format(name))
'information.')

self.debug(
'The bear {bear} raised an exception. If you are the author '
f'The bear {name} raised an exception. If you are the author '
'of this bear, please make sure to catch all exceptions. If '
'not and this error annoys you, you might want to get in '
'contact with the author of this bear.\n\nTraceback '
'information is provided below:\n\n{traceback}'
'\n'.format(bear=name, traceback=traceback.format_exc()))
f'information is provided below:\n\n{traceback.format_exc()}'
'\n')

@staticmethod
def kind():
Expand Down Expand Up @@ -642,8 +643,7 @@ def download_cached_file(self, url, filename):
if exists(filename):
return filename

self.info('Downloading {filename!r} for bear {bearname} from {url}.'
.format(filename=filename, bearname=self.name, url=url))
self.info(f'Downloading {filename!r} for bear {self.name} from {url}.')

response = requests.get(url, stream=True, timeout=20)
response.raise_for_status()
Expand Down
22 changes: 12 additions & 10 deletions coalib/collecting/Collectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ def icollect(file_paths, ignored_globs=None, match_cache={},
for index, glob in enumerate(ignored_globs):
dirname, basename = os.path.split(glob)
if not has_wildcard(dirname) and basename == '**':
logging.warning("Detected trailing globstar in ignore glob '{}'. "
"Please remove the unnecessary '**' from its end."
.format(glob))
logging.warning('Detected trailing globstar in ignore glob '
f"'{glob}'. "
"Please remove the unnecessary '**' from its end.")
ignored_globs[index] = glob.rstrip('*')

for file_path in file_paths:
Expand Down Expand Up @@ -206,21 +206,23 @@ def icollect_bears(bear_dir_glob, bear_globs, kinds, log_printer=None):
yield bear, bear_glob
except pkg_resources.VersionConflict as exception:
log_exception(
('Unable to collect bears from {file} because there '
(f'Unable to collect bears from {matching_file} '
'because there '
'is a conflict with the version of a dependency '
'you have installed. This may be resolved by '
'creating a separate virtual environment for coala '
'or running `pip3 install \"{pkg}\"`. Be aware that '
f'or running `pip3 install \"{exception.req}\"`. '
'Be aware that '
'the latter solution might break other python '
'packages that depend on the currently installed '
'version.').format(file=matching_file,
pkg=exception.req),
'version.'),
exception, log_level=LOG_LEVEL.WARNING)
except BaseException as exception:
log_exception(
'Unable to collect bears from {file}. Probably the '
f'Unable to collect bears from {matching_file}. '
'Probably the '
'file is malformed or the module code raises an '
'exception.'.format(file=matching_file),
'exception.',
exception,
log_level=LOG_LEVEL.WARNING)

Expand Down Expand Up @@ -324,7 +326,7 @@ def collect_bears_by_aspects(aspects, kinds):

if unfulfilled_aspects:
logging.warning('coala cannot find bear that could analyze the '
'following aspects: {}'.format(unfulfilled_aspects))
f'following aspects: {unfulfilled_aspects}')
return bears_found


Expand Down
8 changes: 3 additions & 5 deletions coalib/core/Bear.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,9 +341,8 @@ def check_prerequisites(cls):

if not_installed_requirements:
return 'Following requirements are not installed: ' + ', '.join(
'{} (installable via `{}`)'.format(
requirement.package,
' '.join(requirement.install_command()))
f'{requirement.package} (installable via '
f'`{" ".join(requirement.install_command())}`)'
for requirement in not_installed_requirements)
else:
return True
Expand Down Expand Up @@ -394,8 +393,7 @@ def download_cached_file(cls, url, filename):
if exists(filename):
return filename

logging.info('{}: Downloading {} into {!r}.'
.format(cls.name, url, filename))
logging.info(f'{cls.name}: Downloading {url} into {filename!r}.')

response = requests.get(url, stream=True, timeout=20)
response.raise_for_status()
Expand Down
4 changes: 2 additions & 2 deletions coalib/core/CircularDependencyError.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ def __init__(self, names=None):
The names of the nodes that form a dependency circle.
"""
if names:
msg = 'Circular dependency detected: {names}'.format(
names=' -> '.join(names))
joined_names = ' -> '.join(names)
msg = f'Circular dependency detected: {joined_names}'
else:
msg = 'Circular dependency detected.'
super().__init__(msg)
21 changes: 10 additions & 11 deletions coalib/core/Core.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,9 @@ def _schedule_bears(self, bears):
if self.dependency_tracker.get_dependencies(
bear): # pragma: no cover
logging.warning(
'Dependencies for {!r} not yet resolved, holding back. '
'This should not happen, the dependency tracking system '
'should be smarter. Please report this to the developers.'
.format(bear))
f'Dependencies for {bear!r} not yet resolved, holding back.'
' This should not happen, the dependency tracking system '
'should be smarter. Please report this to the developers.')
else:
futures = set()

Expand Down Expand Up @@ -276,16 +275,15 @@ def _schedule_bears(self, bears):
# early, as the cleanup is also responsible for stopping the
# event-loop when no more tasks do exist.
if not futures:
logging.debug('{!r} scheduled no tasks.'.format(bear))
logging.debug(f'{bear!r} scheduled no tasks.')
bears_without_tasks.append(bear)
continue

for future in futures:
future.add_done_callback(functools.partial(
self._finish_task, bear))

logging.debug('Scheduled {!r} (tasks: {})'.format(
bear, len(futures)))
logging.debug(f'Scheduled {bear!r} (tasks: {len(futures)})')

for bear in bears_without_tasks:
self._cleanup_bear(bear)
Expand Down Expand Up @@ -317,12 +315,13 @@ def _cleanup_bear(self, bear):
# dependencies.
resolved = self.dependency_tracker.are_dependencies_resolved
if not resolved: # pragma: no cover
joined = ', '.join(
repr(dependant) + ' depends on ' + repr(dependency)
for dependency, dependant in self.dependency_tracker)
logging.warning(
'Core finished with run, but it seems some dependencies '
'were unresolved: {}. Ignoring them, but this is a bug, '
'please report it to the developers.'.format(', '.join(
repr(dependant) + ' depends on ' + repr(dependency)
for dependency, dependant in self.dependency_tracker)))
f'were unresolved: {joined}. Ignoring them, but this is a '
'bug, please report it to the developers.')

self.event_loop.stop()

Expand Down
13 changes: 6 additions & 7 deletions coalib/io/FileProxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(self, filename, workspace=None, contents=''):
instance with. Integrity of the content or the
sync state is never checked during initialization.
"""
logging.debug('File proxy for {} created'.format(filename))
logging.debug(f'File proxy for {filename} created')

# The file may not exist yet, hence there is no
# reliable way of knowing if it is a file on the
Expand All @@ -87,8 +87,7 @@ def __str__(self):
Return a string representation of a file proxy
with information about its version and filename.
"""
return '<FileProxy {}, {}>'.format(
self._filename, self._version)
return f'<FileProxy {self._filename}, {self._version}>'

def __hash__(self):
"""
Expand Down Expand Up @@ -118,13 +117,13 @@ def replace(self, contents, version):
self._contents = contents
self._version = version

logging.debug('File proxy for {} updated to version {}.'
.format(self.filename, self.version))
logging.debug(
f'File proxy for {self.filename} '
f'updated to version \'{self.version}\'.')

return True

logging.debug('Updating file proxy for {} failed.'
.format(self.filename))
logging.debug(f'Updating file proxy for {self.filename} failed.')

return False

Expand Down
8 changes: 3 additions & 5 deletions coalib/misc/BuildManPage.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def run(self):
_license = dist.get_license()
appname = self._parser.prog

sections = {'see also': ('Online documentation: {}'.format(homepage)),
sections = {'see also': (f'Online documentation: {homepage}'),
'maintainer(s)': maintainer,
'license': _license}

Expand Down Expand Up @@ -151,9 +151,7 @@ def _bold(string):
return ManPageFormatter._add_format(string, '\\fB', '\\fR')

def _mk_title(self):
return '.TH {0} {1} {2}\n'.format(self._prog,
self._section,
self._today)
return f'.TH {self._prog} {self._section} {self._today}\n'

def _mk_name(self):
return '.SH NAME\n%s\n' % (self._parser.prog)
Expand Down Expand Up @@ -204,7 +202,7 @@ def _mk_footer(self):
footer = []

for section in sorted(sections.keys()):
part = '.SH {}\n {}'.format(section.upper(), sections[section])
part = f'.SH {section.upper()}\n {sections[section]}'
footer.append(part)

return '\n'.join(footer)
Expand Down
11 changes: 6 additions & 5 deletions coalib/misc/Caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,13 +298,14 @@ def get_file_dict(self, filename_list, allow_raw_files=False):
file_dict[filename] = None
continue

logging.warning("Failed to read file '{}'. It seems to contain "
'non-unicode characters. Leaving it out.'
.format(filename))
logging.warning(f"Failed to read file '{filename}'. "
'It seems to contain '
'non-unicode characters. Leaving it out.')

except (OSError, ValueError) as exception:
log_exception("Failed to read file '{}' because of an unknown "
'error. Leaving it out.'.format(filename),
log_exception(f"Failed to read file '{filename}' "
'because of an unknown '
'error. Leaving it out.',
exception,
log_level=LOG_LEVEL.WARNING)

Expand Down
9 changes: 5 additions & 4 deletions coalib/misc/CachingUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ def get_data_path(log_printer, identifier):
os.makedirs(Constants.USER_DATA_DIR, exist_ok=True)
return os.path.join(Constants.USER_DATA_DIR, hash_id(identifier))
except PermissionError:
logging.error("Unable to create user data directory '{}'. Continuing"
' without caching.'.format(Constants.USER_DATA_DIR))
logging.error('Unable to create user data directory '
f"'{Constants.USER_DATA_DIR}'. Continuing"
' without caching.')

return None

Expand Down Expand Up @@ -59,8 +60,8 @@ def delete_files(log_printer, identifiers):
if len(error_files) > 0:
error_files = ', '.join(error_files)
logging.warning('There was a problem deleting the following '
'files: {}. Please delete them manually from '
"'{}'.".format(error_files, Constants.USER_DATA_DIR))
f'files: {error_files}. Please delete them manually '
f"from '{Constants.USER_DATA_DIR}'.")
result = False

return result
Expand Down
2 changes: 1 addition & 1 deletion coalib/misc/DeprecationUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ def check_deprecation(param_list):
"""
for param_name, param_value in param_list.items():
if param_value is not None:
logging.warning('{} parameter is deprecated'.format(param_name))
logging.warning(f'{param_name} parameter is deprecated')
Loading

0 comments on commit 52b9d18

Please sign in to comment.