Skip to content

Commit

Permalink
Convert format strings to f-strings
Browse files Browse the repository at this point in the history
Change-Id: Ie72ee5c4d04c3b149b87a36e41a2cd0e32717f33
  • Loading branch information
xqt committed Nov 2, 2024
1 parent 5436b59 commit 192c430
Show file tree
Hide file tree
Showing 57 changed files with 449 additions and 456 deletions.
9 changes: 4 additions & 5 deletions pywikibot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,8 @@ def Site(code: str | None = None, # noqa: N802
debug(f"Instantiated {interface.__name__} object '{_sites[key]}'")

if _sites[key].code != code:
warn('Site {} instantiated using different code "{}"'
.format(_sites[key], code), UserWarning, 2)
warn(f'Site {_sites[key]} instantiated using different code '
f'"{code}"', UserWarning, 2)

return _sites[key]

Expand Down Expand Up @@ -337,9 +337,8 @@ def remaining() -> tuple[int, datetime.timedelta]:

num, sec = remaining()
if num > 0 and sec.total_seconds() > _config.noisysleep:
output('<<lightblue>>Waiting for {num} pages to be put. '
'Estimated time remaining: {sec}<<default>>'
.format(num=num, sec=sec))
output(f'<<lightblue>>Waiting for {num} pages to be put. '
f'Estimated time remaining: {sec}<<default>>')

exit_queue = None
if _putthread is not threading.current_thread():
Expand Down
5 changes: 2 additions & 3 deletions pywikibot/_wbtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1032,9 +1032,8 @@ def _validate(page: pywikibot.Page, data_site: BaseSite, ending: str,
# check should be enough.
if not page.title().startswith('Data:') \
or not page.title().endswith(ending):
raise ValueError(
"Page must be in 'Data:' namespace and end in '{}' "
'for {}.'.format(ending, label))
raise ValueError(f"Page must be in 'Data:' namespace and end in "
f"'{ending}' for {label}.")

def __init__(self,
page: pywikibot.Page,
Expand Down
34 changes: 17 additions & 17 deletions pywikibot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,8 @@ def set_interface(module_name: str) -> None:
"""
global ui

ui_module = __import__('pywikibot.userinterfaces.{}_interface'
.format(module_name), fromlist=['UI'])
ui_module = __import__(f'pywikibot.userinterfaces.{module_name}_interface',
fromlist=['UI'])
ui = ui_module.UI()
assert ui is not None
atexit.register(ui.flush)
Expand Down Expand Up @@ -1327,8 +1327,8 @@ def _save_page(self, page: pywikibot.page.BasePage,
pywikibot.info(
f'Skipping {page.title()} because of edit conflict')
elif isinstance(e, SpamblacklistError):
pywikibot.info('Cannot change {} because of blacklist '
'entry {}'.format(page.title(), e.url))
pywikibot.info(f'Cannot change {page.title()} because of '
f'blacklist entry {e.url}')
elif isinstance(e, LockedPageError):
pywikibot.info(f'Skipping {page.title()} (locked page)')
else:
Expand Down Expand Up @@ -1390,8 +1390,8 @@ def exit(self) -> None:
for op, count in self.counter.items():
if not count or op == 'read':
continue
pywikibot.info('{} operation time: {:.1f} seconds'
.format(op.capitalize(), write_seconds / count))
pywikibot.info(f'{op.capitalize()} operation time: '
f'{write_seconds / count:.1f} seconds')

# exc_info contains exception from self.run() while terminating
exc_info = sys.exc_info()
Expand Down Expand Up @@ -1454,8 +1454,8 @@ def treat(self, page: Any) -> None:
:class:`page.BasePage`. For other page types the
:attr:`treat_page_type` must be set.
"""
raise NotImplementedError('Method {}.treat() not implemented.'
.format(self.__class__.__name__))
raise NotImplementedError(
f'Method {type(self).__name__}.treat() not implemented.')

def setup(self) -> None:
"""Some initial setup before :meth:`run` operation starts.
Expand Down Expand Up @@ -1814,8 +1814,8 @@ class CurrentPageBot(BaseBot):

def treat_page(self) -> None:
"""Process one page (Abstract method)."""
raise NotImplementedError('Method {}.treat_page() not implemented.'
.format(self.__class__.__name__))
raise NotImplementedError(
f'Method {type(self).__name__}.treat_page() not implemented.')

def treat(self, page: pywikibot.page.BasePage) -> None:
"""Set page to current page and treat that page."""
Expand Down Expand Up @@ -1874,8 +1874,9 @@ def summary_parameters(self) -> dict[str, str]:
def summary_parameters(self, value: dict[str, str]) -> None:
"""Set the i18n dictionary."""
if not isinstance(value, dict):
raise TypeError('"value" must be a dict but {} was found.'
.format(type(value).__name__))
raise TypeError(
f'"value" must be a dict but {type(value).__name__} was found.'
)
self._summary_parameters = value

@summary_parameters.deleter
Expand Down Expand Up @@ -2250,8 +2251,8 @@ def create_item_for_page(self, page: pywikibot.page.BasePage,
:return: pywikibot.ItemPage or None
"""
if not summary:
summary = 'Bot: New item with sitelink from {}'.format(
page.title(as_link=True, insite=self.repo))
summary = ('Bot: New item with sitelink from '
f'{page.title(as_link=True, insite=self.repo)}')

if data is None:
data = {}
Expand Down Expand Up @@ -2327,9 +2328,8 @@ def treat_page_and_item(self, page: pywikibot.page.BasePage,
Must be implemented in subclasses.
"""
raise NotImplementedError('Method {}.treat_page_and_item() not '
'implemented.'
.format(self.__class__.__name__))
raise NotImplementedError(f'Method {type(self).__name__}.'
'treat_page_and_item() not implemented.')


set_interface(config.userinterface)
Expand Down
17 changes: 7 additions & 10 deletions pywikibot/bot_choice.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,8 @@ def format(self, default: str | None = None) -> str:
if self.shortcut == default:
shortcut = self.shortcut.upper()
if index >= 0:
return '{}[{}]{}'.format(
self.option[:index], shortcut,
self.option[index + len(self.shortcut):])
return (f'{self.option[:index]}[{shortcut}]'
f'{self.option[index + len(self.shortcut):]}')
return f'{self.option} [{shortcut}]'

def result(self, value: str) -> Any:
Expand Down Expand Up @@ -592,11 +591,9 @@ def out(self) -> str:
"""Highlighted output section of the text."""
start = max(0, self.start - self.context)
end = min(len(self.text), self.end + self.context)
return '{}<<{color}>>{}<<default>>{}'.format(
self.text[start:self.start],
self.text[self.start:self.end],
self.text[self.end:end],
color=self.color)
return (f'{self.text[start:self.start]}<<{self.color}>>'
f'{self.text[self.start:self.end]}<<default>>'
f'{self.text[self.end:end]}')


class UnhandledAnswer(Exception): # noqa: N818
Expand Down Expand Up @@ -775,8 +772,8 @@ def handle_link(self) -> Any:
if self._new is False:
question += 'be unlinked?'
else:
question += 'target to <<lightpurple>>{}<<default>>?'.format(
self._new.canonical_title())
question += (f'target to <<lightpurple>>'
f'{self._new.canonical_title()}<<default>>?')

choice = pywikibot.input_choice(question, choices,
default=self._default,
Expand Down
12 changes: 6 additions & 6 deletions pywikibot/comms/eventstreams.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ def url(self):
:raises NotImplementedError: no stream types specified
"""
if self._streams is None:
raise NotImplementedError('No streams specified for class {}'
.format(self.__class__.__name__))
raise NotImplementedError(
f'No streams specified for class {type(self).__name__}')
return '{host}{path}/{streams}{since}'.format(
host=self._site.eventstreams_host(),
path=self._site.eventstreams_path(),
Expand All @@ -205,8 +205,8 @@ def set_maximum_items(self, value: int) -> None:
"""
if value is not None:
self._total = int(value)
debug('{}: Set limit (maximum_items) to {}.'
.format(self.__class__.__name__, self._total))
debug(f'{type(self).__name__}: Set limit (maximum_items) to '
f'{self._total}.')

def register_filter(self, *args, **kwargs):
"""Register a filter.
Expand Down Expand Up @@ -363,8 +363,8 @@ def generator(self):
else:
warning(f'Unknown event {event.event} occurred.')

debug('{}: Stopped iterating due to exceeding item limit.'
.format(self.__class__.__name__))
debug(f'{type(self).__name__}: Stopped iterating due to exceeding item'
' limit.')
del self.source


Expand Down
7 changes: 4 additions & 3 deletions pywikibot/comms/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def assign_fake_user_agent(use_fake_user_agent, uri):
if use_fake_user_agent and isinstance(use_fake_user_agent, str):
return use_fake_user_agent # Custom UA.
raise ValueError('Invalid parameter: '
'use_fake_user_agent={}'.format(use_fake_user_agent))
f'use_fake_user_agent={use_fake_user_agent}')

def assign_user_agent(user_agent_format_string):
if not user_agent_format_string or '{' in user_agent_format_string:
Expand Down Expand Up @@ -554,8 +554,9 @@ def _try_decode(content: bytes, encoding: str | None) -> str | None:

if header_codecs and charset_codecs and header_codecs != charset_codecs:
pywikibot.warning(
'Encoding "{}" requested but "{}" received in the '
'response header.'.format(charset, header_encoding))
f'Encoding "{charset}" requested but "{header_encoding}" received'
' in the response header.'
)

_encoding = _try_decode(response.content, header_encoding) \
or _try_decode(response.content, charset)
Expand Down
22 changes: 12 additions & 10 deletions pywikibot/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,9 +397,10 @@ def exists(directory: str) -> bool:
if __no_user_config is None:
assert get_base_dir.__doc__ is not None
exc_text += (
'\nPlease check that {0} is stored in the correct location.'
'\nDirectory where {0} is searched is determined as follows:'
'\n\n '.format(config_file)
f'\nPlease check that {config_file} is stored in the correct'
' location.'
f'\nDirectory where {config_file} is searched is determined as'
' follows:\n\n '
) + get_base_dir.__doc__
raise RuntimeError(exc_text)

Expand Down Expand Up @@ -997,9 +998,10 @@ def _assert_types(


DEPRECATED_VARIABLE = (
'"{{}}" present in our {} is no longer a supported configuration variable '
'and should be removed. Please inform the maintainers if you depend on it.'
.format(user_config_file))
f'"{{}}" present in our {user_config_file} is no longer a supported'
' configuration variable and should be removed. Please inform the'
' maintainers if you depend on it.'
)


def _check_user_config_types(
Expand All @@ -1025,10 +1027,10 @@ def _check_user_config_types(
warn('\n' + fill(DEPRECATED_VARIABLE.format(name)),
_ConfigurationDeprecationWarning)
elif name not in _future_variables:
warn('\n' + fill('Configuration variable "{}" is defined in '
'your {} but unknown. It can be a misspelled '
'one or a variable that is no longer '
'supported.'.format(name, user_config_file)),
warn('\n' + fill(f'Configuration variable "{name}" is defined '
f'in your {user_config_file} but unknown. It'
' can be a misspelled one or a variable that'
' is no longer supported.'),
UserWarning)


Expand Down
22 changes: 11 additions & 11 deletions pywikibot/cosmetic_changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,8 +318,9 @@ def change(self, text: str) -> bool | str:
new_text = self._change(text)
except Exception as e:
if self.ignore == CANCEL.PAGE:
pywikibot.warning('Skipped "{}", because an error occurred.'
.format(self.title))
pywikibot.warning(
f'Skipped "{self.title}", because an error occurred.'
)
pywikibot.error(e)
return False
raise
Expand All @@ -334,8 +335,9 @@ def fixSelfInterwiki(self, text: str) -> str:
Remove their language code prefix.
"""
if not self.talkpage and pywikibot.calledModuleName() != 'interwiki':
interwikiR = re.compile(r'\[\[(?: *:)? *{} *: *([^\[\]\n]*)\]\]'
.format(self.site.code))
interwikiR = re.compile(
rf'\[\[(?: *:)? *{self.site.code} *: *([^\[\]\n]*)\]\]'
)
text = interwikiR.sub(r'[[\1]]', text)
return text

Expand Down Expand Up @@ -640,8 +642,8 @@ def handleOneLink(match: Match[str]) -> str:
# instead of a pipelink
elif (firstcase_label.startswith(firstcase_title)
and trailR.sub('', label[len(titleWithSection):]) == ''):
newLink = '[[{}]]{}'.format(label[:len(titleWithSection)],
label[len(titleWithSection):])
newLink = (f'[[{label[:len(titleWithSection)]}]]'
f'{label[len(titleWithSection):]}')

else:
# Try to capitalize the first letter of the title.
Expand Down Expand Up @@ -891,9 +893,8 @@ def replace_link(match: Match[str]) -> str:

# Match first a non space in the title to prevent that multiple
# spaces at the end without title will be matched by it
title_regex = (r'(?P<link>[^{sep}]+?)'
r'(\s+(?P<title>[^\s].*?))'
.format(sep=separator))
title_regex = (rf'(?P<link>[^{separator}]+?)'
r'(\s+(?P<title>[^\s].*?))')
url_regex = fr'\[\[?{url}?\s*\]\]?'
text = textlib.replaceExcept(
text,
Expand Down Expand Up @@ -1043,8 +1044,7 @@ def fixArabicLetters(self, text: str) -> str:
faChrs = 'ءاآأإئؤبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیةيك' + digits['fa']

# not to let bot edits in latin content
exceptions.append(re.compile('[^{fa}] *?"*? *?, *?[^{fa}]'
.format(fa=faChrs)))
exceptions.append(re.compile(f'[^{faChrs}] *?"*? *?, *?[^{faChrs}]'))
text = textlib.replaceExcept(text, ',', '،', exceptions,
site=self.site)
if self.site.code == 'ckb':
Expand Down
Loading

0 comments on commit 192c430

Please sign in to comment.