Skip to content

Commit

Permalink
CLN:F-string in pandas/_libs/tslibs/*.pyx (pandas-dev#29775)
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaharNaveh authored and proost committed Dec 19, 2019
1 parent ecc0ab3 commit 0498904
Show file tree
Hide file tree
Showing 14 changed files with 127 additions and 158 deletions.
24 changes: 11 additions & 13 deletions pandas/_libs/tslibs/c_timestamp.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ def maybe_integer_op_deprecated(obj):
# GH#22535 add/sub of integers and int-arrays is deprecated
if obj.freq is not None:
warnings.warn("Addition/subtraction of integers and integer-arrays "
"to {cls} is deprecated, will be removed in a future "
f"to {type(obj).__name__} is deprecated, "
"will be removed in a future "
"version. Instead of adding/subtracting `n`, use "
"`n * self.freq`"
.format(cls=type(obj).__name__),
FutureWarning)
, FutureWarning)


cdef class _Timestamp(datetime):
Expand Down Expand Up @@ -144,11 +144,10 @@ cdef class _Timestamp(datetime):
# e.g. tzlocal has no `strftime`
pass

tz = ", tz='{0}'".format(zone) if zone is not None else ""
freq = "" if self.freq is None else ", freq='{0}'".format(self.freqstr)
tz = f", tz='{zone}'" if zone is not None else ""
freq = "" if self.freq is None else f", freq='{self.freqstr}'"

return "Timestamp('{stamp}'{tz}{freq})".format(stamp=stamp,
tz=tz, freq=freq)
return f"Timestamp('{stamp}'{tz}{freq})"

cdef bint _compare_outside_nanorange(_Timestamp self, datetime other,
int op) except -1:
Expand Down Expand Up @@ -370,23 +369,22 @@ cdef class _Timestamp(datetime):

@property
def _repr_base(self) -> str:
return '{date} {time}'.format(date=self._date_repr,
time=self._time_repr)
return f"{self._date_repr} {self._time_repr}"

@property
def _date_repr(self) -> str:
# Ideal here would be self.strftime("%Y-%m-%d"), but
# the datetime strftime() methods require year >= 1900
return '%d-%.2d-%.2d' % (self.year, self.month, self.day)
return f'{self.year}-{self.month:02d}-{self.day:02d}'

@property
def _time_repr(self) -> str:
result = '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
result = f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}'

if self.nanosecond != 0:
result += '.%.9d' % (self.nanosecond + 1000 * self.microsecond)
result += f'.{self.nanosecond + 1000 * self.microsecond:09d}'
elif self.microsecond != 0:
result += '.%.6d' % self.microsecond
result += f'.{self.microsecond:06d}'

return result

Expand Down
8 changes: 4 additions & 4 deletions pandas/_libs/tslibs/conversion.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def datetime_to_datetime64(object[:] values):
iresult[i] = pydatetime_to_dt64(val, &dts)
check_dts_bounds(&dts)
else:
raise TypeError('Unrecognized value type: %s' % type(val))
raise TypeError(f'Unrecognized value type: {type(val)}')

return result, inferred_tz

Expand Down Expand Up @@ -326,8 +326,8 @@ cdef convert_to_tsobject(object ts, object tz, object unit,
raise ValueError("Cannot convert Period to Timestamp "
"unambiguously. Use to_timestamp")
else:
raise TypeError('Cannot convert input [{}] of type {} to '
'Timestamp'.format(ts, type(ts)))
raise TypeError(f'Cannot convert input [{ts}] of type {type(ts)} to '
f'Timestamp')

if tz is not None:
localize_tso(obj, tz)
Expand Down Expand Up @@ -686,7 +686,7 @@ def normalize_date(dt: object) -> datetime:
elif PyDate_Check(dt):
return datetime(dt.year, dt.month, dt.day)
else:
raise TypeError('Unrecognized type: %s' % type(dt))
raise TypeError(f'Unrecognized type: {type(dt)}')


@cython.wraparound(False)
Expand Down
11 changes: 5 additions & 6 deletions pandas/_libs/tslibs/fields.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def get_date_name_field(const int64_t[:] dtindex, object field, object locale=No
out[i] = names[dts.month].capitalize()

else:
raise ValueError("Field {field} not supported".format(field=field))
raise ValueError(f"Field {field} not supported")

return out

Expand Down Expand Up @@ -165,8 +165,7 @@ def get_start_end_field(const int64_t[:] dtindex, object field,

if freqstr:
if freqstr == 'C':
raise ValueError("Custom business days is not supported by {field}"
.format(field=field))
raise ValueError(f"Custom business days is not supported by {field}")
is_business = freqstr[0] == 'B'

# YearBegin(), BYearBegin() use month = starting month of year.
Expand Down Expand Up @@ -373,7 +372,7 @@ def get_start_end_field(const int64_t[:] dtindex, object field,
out[i] = 1

else:
raise ValueError("Field {field} not supported".format(field=field))
raise ValueError(f"Field {field} not supported")

return out.view(bool)

Expand Down Expand Up @@ -537,7 +536,7 @@ def get_date_field(const int64_t[:] dtindex, object field):
elif field == 'is_leap_year':
return isleapyear_arr(get_date_field(dtindex, 'Y'))

raise ValueError("Field {field} not supported".format(field=field))
raise ValueError(f"Field {field} not supported")


@cython.wraparound(False)
Expand Down Expand Up @@ -653,7 +652,7 @@ def get_timedelta_field(const int64_t[:] tdindex, object field):
out[i] = tds.nanoseconds
return out

raise ValueError("Field %s not supported" % field)
raise ValueError(f"Field {field} not supported")


cpdef isleapyear_arr(ndarray years):
Expand Down
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/frequencies.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ cpdef _base_and_stride(str freqstr):
groups = opattern.match(freqstr)

if not groups:
raise ValueError("Could not evaluate {freq}".format(freq=freqstr))
raise ValueError(f"Could not evaluate {freqstr}")

stride = groups.group(1)

Expand Down
12 changes: 5 additions & 7 deletions pandas/_libs/tslibs/nattype.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ cdef class _NaT(datetime):
if is_datetime64_object(other):
return _nat_scalar_rules[op]
else:
raise TypeError('Cannot compare type %r with type %r' %
(type(self).__name__, type(other).__name__))
raise TypeError(f'Cannot compare type {type(self).__name__} '
f'with type {type(other).__name__}')

# Note: instead of passing "other, self, _reverse_ops[op]", we observe
# that `_nat_scalar_rules` is invariant under `_reverse_ops`,
Expand Down Expand Up @@ -150,8 +150,7 @@ cdef class _NaT(datetime):
result = np.empty(other.shape, dtype="datetime64[ns]")
result.fill("NaT")
return result
raise TypeError("Cannot add NaT to ndarray with dtype {dtype}"
.format(dtype=other.dtype))
raise TypeError(f"Cannot add NaT to ndarray with dtype {other.dtype}")

return NotImplemented

Expand Down Expand Up @@ -203,9 +202,8 @@ cdef class _NaT(datetime):
result.fill("NaT")
return result

raise TypeError(
"Cannot subtract NaT from ndarray with dtype {dtype}"
.format(dtype=other.dtype))
raise TypeError(f"Cannot subtract NaT from ndarray with "
f"dtype {other.dtype}")

return NotImplemented

Expand Down
8 changes: 3 additions & 5 deletions pandas/_libs/tslibs/np_datetime.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,9 @@ cdef inline check_dts_bounds(npy_datetimestruct *dts):
error = True

if error:
fmt = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (dts.year, dts.month,
dts.day, dts.hour,
dts.min, dts.sec)
raise OutOfBoundsDatetime(
'Out of bounds nanosecond timestamp: {fmt}'.format(fmt=fmt))
fmt = (f'{dts.year}-{dts.month:02d}-{dts.day:02d} '
f'{dts.hour:02d}:{dts.min:02d}:{dts.sec:02d}')
raise OutOfBoundsDatetime(f'Out of bounds nanosecond timestamp: {fmt}')


# ----------------------------------------------------------------------
Expand Down
19 changes: 8 additions & 11 deletions pandas/_libs/tslibs/offsets.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,16 @@ need_suffix = ['QS', 'BQ', 'BQS', 'YS', 'AS', 'BY', 'BA', 'BYS', 'BAS']

for __prefix in need_suffix:
for _m in MONTHS:
key = '%s-%s' % (__prefix, _m)
key = f'{__prefix}-{_m}'
_offset_to_period_map[key] = _offset_to_period_map[__prefix]

for __prefix in ['A', 'Q']:
for _m in MONTHS:
_alias = '%s-%s' % (__prefix, _m)
_alias = f'{__prefix}-{_m}'
_offset_to_period_map[_alias] = _alias

for _d in DAYS:
_offset_to_period_map['W-%s' % _d] = 'W-%s' % _d
_offset_to_period_map[f'W-{_d}'] = f'W-{_d}'


# ---------------------------------------------------------------------
Expand Down Expand Up @@ -432,9 +432,9 @@ class _BaseOffset:

n_str = ""
if self.n != 1:
n_str = "%s * " % self.n
n_str = f"{self.n} * "

out = '<%s' % n_str + className + plural + self._repr_attrs() + '>'
out = f'<{n_str}{className}{plural}{self._repr_attrs()}>'
return out

def _get_offset_day(self, datetime other):
Expand All @@ -460,16 +460,13 @@ class _BaseOffset:
ValueError if n != int(n)
"""
if util.is_timedelta64_object(n):
raise TypeError('`n` argument must be an integer, '
'got {ntype}'.format(ntype=type(n)))
raise TypeError(f'`n` argument must be an integer, got {type(n)}')
try:
nint = int(n)
except (ValueError, TypeError):
raise TypeError('`n` argument must be an integer, '
'got {ntype}'.format(ntype=type(n)))
raise TypeError(f'`n` argument must be an integer, got {type(n)}')
if n != nint:
raise ValueError('`n` argument must be an integer, '
'got {n}'.format(n=n))
raise ValueError(f'`n` argument must be an integer, got {n}')
return nint

def __setstate__(self, state):
Expand Down
26 changes: 12 additions & 14 deletions pandas/_libs/tslibs/parsing.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ cdef inline object _parse_delimited_date(object date_string, bint dayfirst):
return datetime_new(year, month, day, 0, 0, 0, 0, None), reso
return datetime(year, month, day, 0, 0, 0, 0, None), reso

raise DateParseError("Invalid date specified ({}/{})".format(month, day))
raise DateParseError(f"Invalid date specified ({month}/{day})")


cdef inline bint does_string_look_like_time(object parse_string):
Expand Down Expand Up @@ -311,7 +311,7 @@ cdef parse_datetime_string_with_reso(date_string, freq=None, dayfirst=False,
# TODO: allow raise of errors within instead
raise DateParseError(err)
if parsed is None:
raise DateParseError("Could not parse {dstr}".format(dstr=date_string))
raise DateParseError(f"Could not parse {date_string}")
return parsed, parsed, reso


Expand Down Expand Up @@ -420,18 +420,18 @@ cdef inline object _parse_dateabbr_string(object date_string, object default,
raise ValueError

if not (1 <= quarter <= 4):
msg = ('Incorrect quarterly string is given, quarter must be '
'between 1 and 4: {dstr}')
raise DateParseError(msg.format(dstr=date_string))
raise DateParseError(f'Incorrect quarterly string is given, '
f'quarter must be '
f'between 1 and 4: {date_string}')

if freq is not None:
# hack attack, #1228
try:
mnum = MONTH_NUMBERS[_get_rule_month(freq)] + 1
except (KeyError, ValueError):
msg = ('Unable to retrieve month information from given '
'freq: {freq}'.format(freq=freq))
raise DateParseError(msg)
raise DateParseError(f'Unable to retrieve month '
f'information from given '
f'freq: {freq}')

month = (mnum + (quarter - 1) * 3) % 12 + 1
if month > mnum:
Expand Down Expand Up @@ -464,7 +464,7 @@ cdef inline object _parse_dateabbr_string(object date_string, object default,
except ValueError:
pass

raise ValueError('Unable to parse {0}'.format(date_string))
raise ValueError(f'Unable to parse {date_string}')


cdef dateutil_parse(object timestr, object default, ignoretz=False,
Expand All @@ -484,8 +484,7 @@ cdef dateutil_parse(object timestr, object default, ignoretz=False,
res, _ = res

if res is None:
msg = "Unknown datetime string format, unable to parse: {timestr}"
raise ValueError(msg.format(timestr=timestr))
raise ValueError(f"Unknown datetime string format, unable to parse: {timestr}")

for attr in ["year", "month", "day", "hour",
"minute", "second", "microsecond"]:
Expand All @@ -495,8 +494,7 @@ cdef dateutil_parse(object timestr, object default, ignoretz=False,
reso = attr

if reso is None:
msg = "Unable to parse datetime string: {timestr}"
raise ValueError(msg.format(timestr=timestr))
raise ValueError(f"Unable to parse datetime string: {timestr}")

if reso == 'microsecond':
if repl['microsecond'] == 0:
Expand Down Expand Up @@ -710,7 +708,7 @@ class _timelex:
elif getattr(instream, 'read', None) is None:
raise TypeError(
'Parser must be a string or character stream, not '
'{itype}'.format(itype=instream.__class__.__name__))
f'{type(instream).__name__}')
else:
self.stream = instream.read()

Expand Down
Loading

0 comments on commit 0498904

Please sign in to comment.