Skip to content

Commit 08ca0fa

Browse files
jschendelNo-Stream
authored andcommitted
CLN: replace %s syntax with .format in pandas.core: categorical, common, config, config_init (pandas-dev#17735)
Replaced %s syntax with .format in pandas.core: categorical.py, common.py, config.py, config_init.py. Additionally, made some of the existing positional .format code more explicit.
1 parent 8035766 commit 08ca0fa

File tree

4 files changed

+62
-53
lines changed

4 files changed

+62
-53
lines changed

pandas/core/categorical.py

+20-16
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,8 @@ def __init__(self, values, categories=None, ordered=None, dtype=None,
263263
if dtype == 'category':
264264
dtype = CategoricalDtype(categories, ordered)
265265
else:
266-
raise ValueError("Unknown `dtype` {}".format(dtype))
266+
msg = "Unknown `dtype` {dtype}"
267+
raise ValueError(msg.format(dtype=dtype))
267268
elif categories is not None or ordered is not None:
268269
raise ValueError("Cannot specify both `dtype` and `categories`"
269270
" or `ordered`.")
@@ -931,9 +932,9 @@ def add_categories(self, new_categories, inplace=False):
931932
new_categories = [new_categories]
932933
already_included = set(new_categories) & set(self.dtype.categories)
933934
if len(already_included) != 0:
934-
msg = ("new categories must not include old categories: %s" %
935-
str(already_included))
936-
raise ValueError(msg)
935+
msg = ("new categories must not include old categories: "
936+
"{already_included!s}")
937+
raise ValueError(msg.format(already_included=already_included))
937938
new_categories = list(self.dtype.categories) + list(new_categories)
938939
new_dtype = CategoricalDtype(new_categories, self.ordered)
939940

@@ -989,8 +990,8 @@ def remove_categories(self, removals, inplace=False):
989990
new_categories = [x for x in new_categories if notna(x)]
990991

991992
if len(not_included) != 0:
992-
raise ValueError("removals must all be in old categories: %s" %
993-
str(not_included))
993+
msg = "removals must all be in old categories: {not_included!s}"
994+
raise ValueError(msg.format(not_included=not_included))
994995

995996
return self.set_categories(new_categories, ordered=self.ordered,
996997
rename=False, inplace=inplace)
@@ -1443,7 +1444,8 @@ def sort_values(self, inplace=False, ascending=True, na_position='last'):
14431444
"""
14441445
inplace = validate_bool_kwarg(inplace, 'inplace')
14451446
if na_position not in ['last', 'first']:
1446-
raise ValueError('invalid na_position: {!r}'.format(na_position))
1447+
msg = 'invalid na_position: {na_position!r}'
1448+
raise ValueError(msg.format(na_position=na_position))
14471449

14481450
codes = np.sort(self._codes)
14491451
if not ascending:
@@ -1653,9 +1655,10 @@ def _tidy_repr(self, max_vals=10, footer=True):
16531655
head = self[:num]._get_repr(length=False, footer=False)
16541656
tail = self[-(max_vals - num):]._get_repr(length=False, footer=False)
16551657

1656-
result = '%s, ..., %s' % (head[:-1], tail[1:])
1658+
result = u('{head}, ..., {tail}').format(head=head[:-1], tail=tail[1:])
16571659
if footer:
1658-
result = '%s\n%s' % (result, self._repr_footer())
1660+
result = u('{result}\n{footer}').format(result=result,
1661+
footer=self._repr_footer())
16591662

16601663
return compat.text_type(result)
16611664

@@ -1683,7 +1686,8 @@ def _repr_categories_info(self):
16831686
dtype = getattr(self.categories, 'dtype_str',
16841687
str(self.categories.dtype))
16851688

1686-
levheader = "Categories (%d, %s): " % (len(self.categories), dtype)
1689+
levheader = "Categories ({length}, {dtype}): ".format(
1690+
length=len(self.categories), dtype=dtype)
16871691
width, height = get_terminal_size()
16881692
max_width = get_option("display.width") or width
16891693
if com.in_ipython_frontend():
@@ -1708,7 +1712,8 @@ def _repr_categories_info(self):
17081712

17091713
def _repr_footer(self):
17101714

1711-
return u('Length: %d\n%s') % (len(self), self._repr_categories_info())
1715+
return u('Length: {length}\n{info}').format(
1716+
length=len(self), info=self._repr_categories_info())
17121717

17131718
def _get_repr(self, length=True, na_rep='NaN', footer=True):
17141719
from pandas.io.formats import format as fmt
@@ -1725,9 +1730,8 @@ def __unicode__(self):
17251730
elif len(self._codes) > 0:
17261731
result = self._get_repr(length=len(self) > _maxlen)
17271732
else:
1728-
result = ('[], %s' %
1729-
self._get_repr(length=False,
1730-
footer=True, ).replace("\n", ", "))
1733+
msg = self._get_repr(length=False, footer=True).replace("\n", ", ")
1734+
result = ('[], {repr_msg}'.format(repr_msg=msg))
17311735

17321736
return result
17331737

@@ -1869,8 +1873,8 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
18691873
""" perform the reduction type operation """
18701874
func = getattr(self, name, None)
18711875
if func is None:
1872-
raise TypeError("Categorical cannot perform the operation "
1873-
"{op}".format(op=name))
1876+
msg = 'Categorical cannot perform the operation {op}'
1877+
raise TypeError(msg.format(op=name))
18741878
return func(numeric_only=numeric_only, **kwds)
18751879

18761880
def min(self, numeric_only=None, **kwargs):

pandas/core/common.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,8 @@ def __init__(self, class_instance):
9696
self.class_instance = class_instance
9797

9898
def __str__(self):
99-
return ("This method must be defined in the concrete class of %s" %
100-
self.class_instance.__class__.__name__)
99+
msg = "This method must be defined in the concrete class of {name}"
100+
return (msg.format(name=self.class_instance.__class__.__name__))
101101

102102

103103
def flatten(l):
@@ -150,8 +150,8 @@ def _maybe_match_name(a, b):
150150
def _get_info_slice(obj, indexer):
151151
"""Slice the info axis of `obj` with `indexer`."""
152152
if not hasattr(obj, '_info_axis_number'):
153-
raise TypeError('object of type %r has no info axis' %
154-
type(obj).__name__)
153+
msg = 'object of type {typ!r} has no info axis'
154+
raise TypeError(msg.format(typ=type(obj).__name__))
155155
slices = [slice(None)] * obj.ndim
156156
slices[obj._info_axis_number] = indexer
157157
return tuple(slices)
@@ -214,8 +214,8 @@ def _mut_exclusive(**kwargs):
214214
label1, val1 = item1
215215
label2, val2 = item2
216216
if val1 is not None and val2 is not None:
217-
raise TypeError('mutually exclusive arguments: %r and %r' %
218-
(label1, label2))
217+
msg = 'mutually exclusive arguments: {label1!r} and {label2!r}'
218+
raise TypeError(msg.format(label1=label1, label2=label2))
219219
elif val1 is not None:
220220
return val1
221221
else:
@@ -517,7 +517,7 @@ def standardize_mapping(into):
517517
collections.defaultdict, into.default_factory)
518518
into = type(into)
519519
if not issubclass(into, collections.Mapping):
520-
raise TypeError('unsupported type: {}'.format(into))
520+
raise TypeError('unsupported type: {into}'.format(into=into))
521521
elif into == collections.defaultdict:
522522
raise TypeError(
523523
'to_dict() only accepts initialized defaultdicts')

pandas/core/config.py

+31-26
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def _get_single_key(pat, silent):
8080
if len(keys) == 0:
8181
if not silent:
8282
_warn_if_deprecated(pat)
83-
raise OptionError('No such keys(s): %r' % pat)
83+
raise OptionError('No such keys(s): {pat!r}'.format(pat=pat))
8484
if len(keys) > 1:
8585
raise OptionError('Pattern matched multiple keys')
8686
key = keys[0]
@@ -112,8 +112,8 @@ def _set_option(*args, **kwargs):
112112
silent = kwargs.pop('silent', False)
113113

114114
if kwargs:
115-
raise TypeError('_set_option() got an unexpected keyword '
116-
'argument "{0}"'.format(list(kwargs.keys())[0]))
115+
msg = '_set_option() got an unexpected keyword argument "{kwarg}"'
116+
raise TypeError(msg.format(list(kwargs.keys())[0]))
117117

118118
for k, v in zip(args[::2], args[1::2]):
119119
key = _get_single_key(k, silent)
@@ -436,9 +436,11 @@ def register_option(key, defval, doc='', validator=None, cb=None):
436436
key = key.lower()
437437

438438
if key in _registered_options:
439-
raise OptionError("Option '%s' has already been registered" % key)
439+
msg = "Option '{key}' has already been registered"
440+
raise OptionError(msg.format(key=key))
440441
if key in _reserved_keys:
441-
raise OptionError("Option '%s' is a reserved key" % key)
442+
msg = "Option '{key}' is a reserved key"
443+
raise OptionError(msg.format(key=key))
442444

443445
# the default value should be legal
444446
if validator:
@@ -449,22 +451,21 @@ def register_option(key, defval, doc='', validator=None, cb=None):
449451

450452
for k in path:
451453
if not bool(re.match('^' + tokenize.Name + '$', k)):
452-
raise ValueError("%s is not a valid identifier" % k)
454+
raise ValueError("{k} is not a valid identifier".format(k=k))
453455
if keyword.iskeyword(k):
454-
raise ValueError("%s is a python keyword" % k)
456+
raise ValueError("{k} is a python keyword".format(k=k))
455457

456458
cursor = _global_config
459+
msg = "Path prefix to option '{option}' is already an option"
457460
for i, p in enumerate(path[:-1]):
458461
if not isinstance(cursor, dict):
459-
raise OptionError("Path prefix to option '%s' is already an option"
460-
% '.'.join(path[:i]))
462+
raise OptionError(msg.format(option='.'.join(path[:i])))
461463
if p not in cursor:
462464
cursor[p] = {}
463465
cursor = cursor[p]
464466

465467
if not isinstance(cursor, dict):
466-
raise OptionError("Path prefix to option '%s' is already an option" %
467-
'.'.join(path[:-1]))
468+
raise OptionError(msg.format(option='.'.join(path[:-1])))
468469

469470
cursor[path[-1]] = defval # initialize
470471

@@ -516,8 +517,8 @@ def deprecate_option(key, msg=None, rkey=None, removal_ver=None):
516517
key = key.lower()
517518

518519
if key in _deprecated_options:
519-
raise OptionError("Option '%s' has already been defined as deprecated."
520-
% key)
520+
msg = "Option '{key}' has already been defined as deprecated."
521+
raise OptionError(msg.format(key=key))
521522

522523
_deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)
523524

@@ -614,11 +615,12 @@ def _warn_if_deprecated(key):
614615
print(d.msg)
615616
warnings.warn(d.msg, DeprecationWarning)
616617
else:
617-
msg = "'%s' is deprecated" % key
618+
msg = "'{key}' is deprecated".format(key=key)
618619
if d.removal_ver:
619-
msg += ' and will be removed in %s' % d.removal_ver
620+
msg += (' and will be removed in {version}'
621+
.format(version=d.removal_ver))
620622
if d.rkey:
621-
msg += ", please use '%s' instead." % d.rkey
623+
msg += ", please use '{rkey}' instead.".format(rkey=d.rkey)
622624
else:
623625
msg += ', please refrain from using it.'
624626

@@ -633,20 +635,21 @@ def _build_option_description(k):
633635
o = _get_registered_option(k)
634636
d = _get_deprecated_option(k)
635637

636-
s = u('%s ') % k
638+
s = u('{k} ').format(k=k)
637639

638640
if o.doc:
639641
s += '\n'.join(o.doc.strip().split('\n'))
640642
else:
641643
s += 'No description available.'
642644

643645
if o:
644-
s += u('\n [default: %s] [currently: %s]') % (o.defval,
645-
_get_option(k, True))
646+
s += (u('\n [default: {default}] [currently: {current}]')
647+
.format(default=o.defval, current=_get_option(k, True)))
646648

647649
if d:
648650
s += u('\n (Deprecated')
649-
s += (u(', use `%s` instead.') % d.rkey if d.rkey else '')
651+
s += (u(', use `{rkey}` instead.')
652+
.format(rkey=d.rkey if d.rkey else ''))
650653
s += u(')')
651654

652655
s += '\n\n'
@@ -718,7 +721,7 @@ def config_prefix(prefix):
718721

719722
def wrap(func):
720723
def inner(key, *args, **kwds):
721-
pkey = '%s.%s' % (prefix, key)
724+
pkey = '{prefix}.{key}'.format(prefix=prefix, key=key)
722725
return func(pkey, *args, **kwds)
723726

724727
return inner
@@ -754,7 +757,8 @@ def is_type_factory(_type):
754757

755758
def inner(x):
756759
if type(x) != _type:
757-
raise ValueError("Value must have type '%s'" % str(_type))
760+
msg = "Value must have type '{typ!s}'"
761+
raise ValueError(msg.format(typ=_type))
758762

759763
return inner
760764

@@ -777,11 +781,12 @@ def is_instance_factory(_type):
777781
from pandas.io.formats.printing import pprint_thing
778782
type_repr = "|".join(map(pprint_thing, _type))
779783
else:
780-
type_repr = "'%s'" % _type
784+
type_repr = "'{typ}'".format(typ=_type)
781785

782786
def inner(x):
783787
if not isinstance(x, _type):
784-
raise ValueError("Value must be an instance of %s" % type_repr)
788+
msg = "Value must be an instance of {type_repr}"
789+
raise ValueError(msg.format(type_repr=type_repr))
785790

786791
return inner
787792

@@ -797,10 +802,10 @@ def inner(x):
797802

798803
if not any([c(x) for c in callables]):
799804
pp_values = pp("|".join(lmap(pp, legal_values)))
800-
msg = "Value must be one of {0}".format(pp_values)
805+
msg = "Value must be one of {pp_values}"
801806
if len(callables):
802807
msg += " or a callable"
803-
raise ValueError(msg)
808+
raise ValueError(msg.format(pp_values=pp_values))
804809

805810
return inner
806811

pandas/core/config_init.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -453,10 +453,10 @@ def use_inf_as_na_cb(key):
453453
cf.register_option(ext + '.writer', default, doc, validator=str)
454454

455455
def _register_xlsx(engine, other):
456-
cf.register_option('xlsx.writer', engine,
457-
writer_engine_doc.format(ext='xlsx', default=engine,
458-
others=", '%s'" % other),
459-
validator=str)
456+
others = ", '{other}'".format(other=other)
457+
doc = writer_engine_doc.format(ext='xlsx', default=engine,
458+
others=others)
459+
cf.register_option('xlsx.writer', engine, doc, validator=str)
460460

461461
try:
462462
# better memory footprint

0 commit comments

Comments
 (0)