Skip to content

Commit

Permalink
[cleanup] Consistently use string's format()
Browse files Browse the repository at this point in the history
String formatting from PEP3101 is intended to replace printf style
formatting [1][2]. date.py, i18n.py, and a few scripts have especially
sophisticated usage so leaving those be.

This also drops unnecessary index references [3] and repr() [4] from format
calls.

[1] https://www.python.org/dev/peps/pep-3101/#abstract
[2] https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

[3] The following are identical...

    >>> '{0} {1}'.format('arg1', 'arg2')
    >>> '{} {}'.format('arg1', 'arg2')

[4] The following are identical...

    >>> 'repr value: {}.format(repr(my_arg))
    >>> 'repr value: {!r}.format(my_arg)

Change-Id: I5191814201ca1f4dcfa3a6c587be0dd2b9fe76ff
  • Loading branch information
atagar committed May 7, 2021
1 parent 8324dcf commit fd605f0
Show file tree
Hide file tree
Showing 123 changed files with 1,215 additions and 1,171 deletions.
14 changes: 7 additions & 7 deletions generate_user_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def change_base_dir():
try:
os.mkdir(new_base, pywikibot.config.private_files_permission)
except Exception as e:
pywikibot.error('directory creation failed: {0}'.format(e))
pywikibot.error('directory creation failed: {}'.format(e))
continue
pywikibot.output('Created new directory.')
break
Expand All @@ -80,11 +80,11 @@ def change_base_dir():
return new_base

msg = fill("""WARNING: Your user files will be created in the directory
'%(new_base)s' you have chosen. To access these files, you will either have
to use the argument "-dir:%(new_base)s" every time you run the bot, or set
'{new_base}' you have chosen. To access these files, you will either have
to use the argument "-dir:{new_base}" every time you run the bot, or set
the environment variable "PYWIKIBOT_DIR" equal to this directory name in
your operating system. See your operating system documentation for how to
set environment variables.""" % {'new_base': new_base}, width=76)
set environment variables.""".format(new_base=new_base), width=76)
pywikibot.output(msg)
if pywikibot.input_yn('Is this OK?', default=False, automatic_quit=False):
return new_base
Expand Down Expand Up @@ -140,7 +140,7 @@ def get_site_and_lang(default_family: Optional[str] = 'wikipedia',
.format(fam.name))
default_lang = None
elif len(known_langs) == 1:
pywikibot.output('The only known language: {0}'.format(known_langs[0]))
pywikibot.output('The only known language: {}'.format(known_langs[0]))
default_lang = known_langs[0]
else:
pywikibot.output('This is the list of known languages:')
Expand All @@ -162,7 +162,7 @@ def get_site_and_lang(default_family: Optional[str] = 'wikipedia',
default=False, automatic_quit=False):
mycode = None

message = 'Username on {0}:{1}'.format(mycode, fam.name)
message = 'Username on {}:{}'.format(mycode, fam.name)
username = pywikibot.input(message, default=default_username, force=force)
# Escape ''s
if username:
Expand Down Expand Up @@ -341,7 +341,7 @@ def create_user_config(main_family, main_code, main_username, force=False):
botpasswords='password_file = ' + ('"{}"'.format(PASS_BASENAME)
if botpasswords
else 'None')))
pywikibot.output("'%s' written." % _fnc)
pywikibot.output("'{}' written.".format(_fnc))
except BaseException:
if os.path.exists(_fnc):
os.remove(_fnc)
Expand Down
6 changes: 3 additions & 3 deletions pwb.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def find_filename(filename):
script_paths = config.user_script_paths + script_paths
else:
warn("'user_script_paths' must be a list,\n"
'found: {0}. Ignoring this setting.'
'found: {}. Ignoring this setting.'
.format(type(config.user_script_paths)))

path_list = []
Expand Down Expand Up @@ -348,8 +348,8 @@ def main():
try:
import_module(file_package)
except ImportError as e:
warn('Parent module %s not found: %s'
% (file_package, e), ImportWarning)
warn('Parent module {} not found: {}'
.format(file_package, e), ImportWarning)

help_option = any(arg.startswith('-help:') or arg == '-help'
for arg in script_args)
Expand Down
41 changes: 21 additions & 20 deletions pywikibot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import re
import threading
import time

from contextlib import suppress
from decimal import Decimal
from queue import Queue
Expand Down Expand Up @@ -48,8 +47,8 @@
)
from pywikibot.diff import PatchManager
from pywikibot.exceptions import (
CoordinateGlobeUnknownError,
DEPRECATED_EXCEPTIONS,
CoordinateGlobeUnknownError,
)
from pywikibot.family import AutoFamily, Family
from pywikibot.i18n import translate
Expand All @@ -67,8 +66,9 @@
from pywikibot.tools import (
ModuleDeprecationWrapper as _ModuleDeprecationWrapper,
)
from pywikibot.tools import classproperty, normalize_username
from pywikibot.tools import classproperty
from pywikibot.tools import deprecate_arg as _deprecate_arg
from pywikibot.tools import normalize_username
from pywikibot.tools.formatter import color_format


Expand Down Expand Up @@ -137,7 +137,7 @@ def _ISO8601Format(cls, sep: str = 'T') -> str:
@return: ISO8601 format string
"""
assert len(sep) == 1
return '%Y-%m-%d{0}%H:%M:%SZ'.format(sep)
return '%Y-%m-%d{}%H:%M:%SZ'.format(sep)

@classmethod
def fromISOformat(cls, ts, sep: str = 'T'):
Expand Down Expand Up @@ -257,8 +257,8 @@ def entity(self):
if not self._entity:
if self.globe not in self.site.globes():
raise CoordinateGlobeUnknownError(
'%s is not supported in Wikibase yet.'
% self.globe)
'{} is not supported in Wikibase yet.'
.format(self.globe))
return self.site.globes()[self.globe]

if isinstance(self._entity, ItemPage):
Expand Down Expand Up @@ -504,7 +504,8 @@ def __init__(self,
if site is None:
site = Site().data_repository()
if site is None:
raise ValueError('Site %s has no data repository' % Site())
raise ValueError('Site {} has no data repository'
.format(Site()))
calendarmodel = site.calendarmodel()
self.calendarmodel = calendarmodel

Expand All @@ -516,7 +517,7 @@ def __init__(self,
elif precision in self.PRECISION:
self.precision = self.PRECISION[precision]
else:
raise ValueError('Invalid precision: "%s"' % precision)
raise ValueError('Invalid precision: "{}"'.format(precision))

@classmethod
def fromTimestr(cls,
Expand Down Expand Up @@ -551,7 +552,7 @@ def fromTimestr(cls,
match = re.match(r'([-+]?\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z',
datetimestr)
if not match:
raise ValueError("Invalid format: '%s'" % datetimestr)
raise ValueError("Invalid format: '{}'".format(datetimestr))
t = match.groups()
return cls(int(t[0]), int(t[1]), int(t[2]),
int(t[3]), int(t[4]), int(t[5]),
Expand Down Expand Up @@ -903,10 +904,10 @@ def _validate(page, data_site, ending: str, label: str):
# validate page is on the right site, and that site supports the type
if not data_site:
raise ValueError(
'The provided site does not support {0}.'.format(label))
'The provided site does not support {}.'.format(label))
if page.site != data_site:
raise ValueError(
'Page must be on the {0} repository site.'.format(label))
'Page must be on the {} repository site.'.format(label))

# validate page title fulfills hard-coded Wikibase requirement
# pcre regexp: '/^Data:[^\\[\\]#\\\:{|}]+\.map$/u' for geo-shape
Expand All @@ -916,8 +917,8 @@ def _validate(page, data_site, ending: str, label: str):
if not page.title().startswith('Data:') \
or not page.title().endswith(ending):
raise ValueError(
"Page must be in 'Data:' namespace and end in '{0}' "
'for {1}.'.format(ending, label))
"Page must be in 'Data:' namespace and end in '{}' "
'for {}.'.format(ending, label))

def __init__(self, page, site: Optional[DataSite] = None):
"""
Expand Down Expand Up @@ -1148,23 +1149,23 @@ def Site(code: Optional[str] = None, fam=None, user: Optional[str] = None, *,
try:
tmp = __import__('pywikibot.site', fromlist=[interface])
except ImportError:
raise ValueError('Invalid interface name: {0}'.format(interface))
raise ValueError('Invalid interface name: {}'.format(interface))
else:
interface = getattr(tmp, interface)

if not issubclass(interface, BaseSite):
warning('Site called with interface=%s' % interface.__name__)
warning('Site called with interface={}'.format(interface.__name__))

user = normalize_username(user)
key = '%s:%s:%s:%s' % (interface.__name__, fam, code, user)
key = '{}:{}:{}:{}'.format(interface.__name__, fam, code, user)
if key not in _sites or not isinstance(_sites[key], interface):
_sites[key] = interface(code=code, fam=fam, user=user)
debug("Instantiated %s object '%s'"
% (interface.__name__, _sites[key]), _logger)
debug("Instantiated {} object '{}'"
.format(interface.__name__, _sites[key]), _logger)

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

return _sites[key]

Expand Down
4 changes: 2 additions & 2 deletions pywikibot/_wbtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ def __repr__(self):
assert all(isinstance(item, str) for item in self._items)

values = ((attr, getattr(self, attr)) for attr in self._items)
attrs = ', '.join('{0}={1}'.format(attr, value)
attrs = ', '.join('{}={}'.format(attr, value)
for attr, value in values)
return '{0}({1})'.format(self.__class__.__name__, attrs)
return '{}({})'.format(self.__class__.__name__, attrs)

def __eq__(self, other):
if isinstance(other, self.__class__):
Expand Down
Loading

0 comments on commit fd605f0

Please sign in to comment.