Skip to content

Commit

Permalink
CLN: replace %s syntax with .format in pandas.core: categorical, comm…
Browse files Browse the repository at this point in the history
…on, config, config_init

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.
  • Loading branch information
jschendel committed Oct 2, 2017
1 parent 408ecd2 commit 687be9a
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 53 deletions.
36 changes: 20 additions & 16 deletions pandas/core/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,8 @@ def __init__(self, values, categories=None, ordered=None, dtype=None,
if dtype == 'category':
dtype = CategoricalDtype(categories, ordered)
else:
raise ValueError("Unknown `dtype` {}".format(dtype))
msg = "Unknown `dtype` {dtype}"
raise ValueError(msg.format(dtype=dtype))
elif categories is not None or ordered is not None:
raise ValueError("Cannot specify both `dtype` and `categories`"
" or `ordered`.")
Expand Down Expand Up @@ -931,9 +932,9 @@ def add_categories(self, new_categories, inplace=False):
new_categories = [new_categories]
already_included = set(new_categories) & set(self.dtype.categories)
if len(already_included) != 0:
msg = ("new categories must not include old categories: %s" %
str(already_included))
raise ValueError(msg)
msg = ("new categories must not include old categories: "
"{already_included!s}")
raise ValueError(msg.format(already_included=already_included))
new_categories = list(self.dtype.categories) + list(new_categories)
new_dtype = CategoricalDtype(new_categories, self.ordered)

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

if len(not_included) != 0:
raise ValueError("removals must all be in old categories: %s" %
str(not_included))
msg = "removals must all be in old categories: {not_included!s}"
raise ValueError(msg.format(not_included=not_included))

return self.set_categories(new_categories, ordered=self.ordered,
rename=False, inplace=inplace)
Expand Down Expand Up @@ -1443,7 +1444,8 @@ def sort_values(self, inplace=False, ascending=True, na_position='last'):
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if na_position not in ['last', 'first']:
raise ValueError('invalid na_position: {!r}'.format(na_position))
msg = 'invalid na_position: {na_position!r}'
raise ValueError(msg.format(na_position=na_position))

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

result = '%s, ..., %s' % (head[:-1], tail[1:])
result = u('{head}, ..., {tail}').format(head=head[:-1], tail=tail[1:])
if footer:
result = '%s\n%s' % (result, self._repr_footer())
result = u('{result}\n{footer}').format(result=result,
footer=self._repr_footer())

return compat.text_type(result)

Expand Down Expand Up @@ -1683,7 +1686,8 @@ def _repr_categories_info(self):
dtype = getattr(self.categories, 'dtype_str',
str(self.categories.dtype))

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

def _repr_footer(self):

return u('Length: %d\n%s') % (len(self), self._repr_categories_info())
return u('Length: {length}\n{info}').format(
length=len(self), info=self._repr_categories_info())

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

return result

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

def min(self, numeric_only=None, **kwargs):
Expand Down
14 changes: 7 additions & 7 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ def __init__(self, class_instance):
self.class_instance = class_instance

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


def flatten(l):
Expand Down Expand Up @@ -150,8 +150,8 @@ def _maybe_match_name(a, b):
def _get_info_slice(obj, indexer):
"""Slice the info axis of `obj` with `indexer`."""
if not hasattr(obj, '_info_axis_number'):
raise TypeError('object of type %r has no info axis' %
type(obj).__name__)
msg = 'object of type {typ!r} has no info axis'
raise TypeError(msg.format(typ=type(obj).__name__))
slices = [slice(None)] * obj.ndim
slices[obj._info_axis_number] = indexer
return tuple(slices)
Expand Down Expand Up @@ -214,8 +214,8 @@ def _mut_exclusive(**kwargs):
label1, val1 = item1
label2, val2 = item2
if val1 is not None and val2 is not None:
raise TypeError('mutually exclusive arguments: %r and %r' %
(label1, label2))
msg = 'mutually exclusive arguments: {label1!r} and {label2!r}'
raise TypeError(msg.format(label1=label1, label2=label2))
elif val1 is not None:
return val1
else:
Expand Down Expand Up @@ -517,7 +517,7 @@ def standardize_mapping(into):
collections.defaultdict, into.default_factory)
into = type(into)
if not issubclass(into, collections.Mapping):
raise TypeError('unsupported type: {}'.format(into))
raise TypeError('unsupported type: {into}'.format(into=into))
elif into == collections.defaultdict:
raise TypeError(
'to_dict() only accepts initialized defaultdicts')
Expand Down
57 changes: 31 additions & 26 deletions pandas/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def _get_single_key(pat, silent):
if len(keys) == 0:
if not silent:
_warn_if_deprecated(pat)
raise OptionError('No such keys(s): %r' % pat)
raise OptionError('No such keys(s): {pat!r}'.format(pat=pat))
if len(keys) > 1:
raise OptionError('Pattern matched multiple keys')
key = keys[0]
Expand Down Expand Up @@ -112,8 +112,8 @@ def _set_option(*args, **kwargs):
silent = kwargs.pop('silent', False)

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

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

if key in _registered_options:
raise OptionError("Option '%s' has already been registered" % key)
msg = "Option '{key}' has already been registered"
raise OptionError(msg.format(key=key))
if key in _reserved_keys:
raise OptionError("Option '%s' is a reserved key" % key)
msg = "Option '{key}' is a reserved key"
raise OptionError(msg.format(key=key))

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

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

cursor = _global_config
msg = "Path prefix to option '{option}' is already an option"
for i, p in enumerate(path[:-1]):
if not isinstance(cursor, dict):
raise OptionError("Path prefix to option '%s' is already an option"
% '.'.join(path[:i]))
raise OptionError(msg.format(option='.'.join(path[:i])))
if p not in cursor:
cursor[p] = {}
cursor = cursor[p]

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

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

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

if key in _deprecated_options:
raise OptionError("Option '%s' has already been defined as deprecated."
% key)
msg = "Option '{key}' has already been defined as deprecated."
raise OptionError(msg.format(key=key))

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

Expand Down Expand Up @@ -614,11 +615,12 @@ def _warn_if_deprecated(key):
print(d.msg)
warnings.warn(d.msg, DeprecationWarning)
else:
msg = "'%s' is deprecated" % key
msg = "'{key}' is deprecated".format(key=key)
if d.removal_ver:
msg += ' and will be removed in %s' % d.removal_ver
msg += (' and will be removed in {version}'
.format(version=d.removal_ver))
if d.rkey:
msg += ", please use '%s' instead." % d.rkey
msg += ", please use '{rkey}' instead.".format(rkey=d.rkey)
else:
msg += ', please refrain from using it.'

Expand All @@ -633,20 +635,21 @@ def _build_option_description(k):
o = _get_registered_option(k)
d = _get_deprecated_option(k)

s = u('%s ') % k
s = u('{k} ').format(k=k)

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

if o:
s += u('\n [default: %s] [currently: %s]') % (o.defval,
_get_option(k, True))
s += (u('\n [default: {default}] [currently: {current}]')
.format(default=o.defval, current=_get_option(k, True)))

if d:
s += u('\n (Deprecated')
s += (u(', use `%s` instead.') % d.rkey if d.rkey else '')
s += (u(', use `{rkey}` instead.')
.format(rkey=d.rkey if d.rkey else ''))
s += u(')')

s += '\n\n'
Expand Down Expand Up @@ -718,7 +721,7 @@ def config_prefix(prefix):

def wrap(func):
def inner(key, *args, **kwds):
pkey = '%s.%s' % (prefix, key)
pkey = '{prefix}.{key}'.format(prefix=prefix, key=key)
return func(pkey, *args, **kwds)

return inner
Expand Down Expand Up @@ -754,7 +757,8 @@ def is_type_factory(_type):

def inner(x):
if type(x) != _type:
raise ValueError("Value must have type '%s'" % str(_type))
msg = "Value must have type '{typ!s}'"
raise ValueError(msg.format(typ=_type))

return inner

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

def inner(x):
if not isinstance(x, _type):
raise ValueError("Value must be an instance of %s" % type_repr)
msg = "Value must be an instance of {type_repr}"
raise ValueError(msg.format(type_repr=type_repr))

return inner

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

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

return inner

Expand Down
8 changes: 4 additions & 4 deletions pandas/core/config_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,10 +453,10 @@ def use_inf_as_na_cb(key):
cf.register_option(ext + '.writer', default, doc, validator=str)

def _register_xlsx(engine, other):
cf.register_option('xlsx.writer', engine,
writer_engine_doc.format(ext='xlsx', default=engine,
others=", '%s'" % other),
validator=str)
others = ", '{other}'".format(other=other)
doc = writer_engine_doc.format(ext='xlsx', default=engine,
others=others)
cf.register_option('xlsx.writer', engine, doc, validator=str)

try:
# better memory footprint
Expand Down

0 comments on commit 687be9a

Please sign in to comment.