From 4ead557eeeb871c9561753a8e964e45d571407fe Mon Sep 17 00:00:00 2001 From: MomIsBestFriend <> Date: Thu, 21 Nov 2019 23:13:04 +0200 Subject: [PATCH] F-string --- pandas/_libs/tslibs/c_timestamp.pyx | 30 ++++++------- pandas/_libs/tslibs/conversion.pyx | 8 ++-- pandas/_libs/tslibs/fields.pyx | 11 +++-- pandas/_libs/tslibs/frequencies.pyx | 2 +- pandas/_libs/tslibs/nattype.pyx | 12 +++-- pandas/_libs/tslibs/np_datetime.pyx | 8 ++-- pandas/_libs/tslibs/offsets.pyx | 19 ++++---- pandas/_libs/tslibs/parsing.pyx | 28 ++++++------ pandas/_libs/tslibs/period.pyx | 44 +++++++++---------- pandas/_libs/tslibs/strptime.pyx | 32 +++++++------- pandas/_libs/tslibs/timedeltas.pyx | 66 +++++++++++----------------- pandas/_libs/tslibs/timestamps.pyx | 12 ++--- pandas/_libs/tslibs/timezones.pyx | 4 +- pandas/_libs/tslibs/tzconversion.pyx | 16 +++---- 14 files changed, 130 insertions(+), 162 deletions(-) diff --git a/pandas/_libs/tslibs/c_timestamp.pyx b/pandas/_libs/tslibs/c_timestamp.pyx index 8512b34b9e78c..3748a02bffe9d 100644 --- a/pandas/_libs/tslibs/c_timestamp.pyx +++ b/pandas/_libs/tslibs/c_timestamp.pyx @@ -54,12 +54,12 @@ class NullFrequencyError(ValueError): 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 " - "version. Instead of adding/subtracting `n`, use " - "`n * self.freq`" - .format(cls=type(obj).__name__), - FutureWarning) + warnings.warn(f"Addition/subtraction of integers and integer-arrays " + f"to {type(obj).__name__} is deprecated, " + f"will be removed in a future " + f"version. Instead of adding/subtracting `n`, use " + f"`n * self.freq`" + , FutureWarning) cdef class _Timestamp(datetime): @@ -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: @@ -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 diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index bd74180403ad9..c5315219b8422 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -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 @@ -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) @@ -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) diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 8f5c8d10776df..dfed8d06530aa 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -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 @@ -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. @@ -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) @@ -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) @@ -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): diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx index b29c841896072..660f4ddcec736 100644 --- a/pandas/_libs/tslibs/frequencies.pyx +++ b/pandas/_libs/tslibs/frequencies.pyx @@ -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) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 3ddce28fb6dd1..6e5e62e77b4b1 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -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`, @@ -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 @@ -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 diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index e76f84265a327..b9406074bb130 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -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}') # ---------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 434252677f1a1..68a0a4a403c81 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -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}' # --------------------------------------------------------------------- @@ -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): @@ -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): diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 8fe724fa2f6f7..74de0bbadbcce 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -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): @@ -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 @@ -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: @@ -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, @@ -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"]: @@ -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: @@ -709,8 +707,8 @@ class _timelex: self.stream = instream 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'Parser must be a string or character stream, not ' + f'{instream.__class__.__name__}') else: self.stream = instream.read() diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 2512fdb891e3e..b7ff0e1bb18f5 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1227,7 +1227,7 @@ def period_format(int64_t value, int freq, object fmt=None): elif freq_group == 12000: # NANOSEC fmt = b'%Y-%m-%d %H:%M:%S.%n' else: - raise ValueError('Unknown freq: {freq}'.format(freq=freq)) + raise ValueError(f'Unknown freq: {freq}') return _period_strftime(value, freq, fmt) @@ -1273,17 +1273,17 @@ cdef object _period_strftime(int64_t value, int freq, object fmt): raise ValueError('Unable to get quarter and year') if i == 0: - repl = '%d' % quarter + repl = str(quarter) elif i == 1: # %f, 2-digit year - repl = '%.2d' % (year % 100) + repl = f'{year % 100:02d}' elif i == 2: - repl = '%d' % year + repl = str(year) elif i == 3: - repl = '%03d' % (value % 1000) + repl = f'{value % 1_000:03d}' elif i == 4: - repl = '%06d' % (value % 1000000) + repl = f'{value % 1_000_000:06d}' elif i == 5: - repl = '%09d' % (value % 1000000000) + repl = f'{value % 1_000_000_000:09d}' result = result.replace(str_extra_fmts[i], repl) @@ -1391,7 +1391,7 @@ def get_period_field_arr(int code, int64_t[:] arr, int freq): func = _get_accessor_func(code) if func is NULL: - raise ValueError('Unrecognized period code: {code}'.format(code=code)) + raise ValueError(f'Unrecognized period code: {code}') sz = len(arr) out = np.empty(sz, dtype=np.int64) @@ -1578,9 +1578,8 @@ cdef class _Period: freq = to_offset(freq) if freq.n <= 0: - raise ValueError('Frequency must be positive, because it' - ' represents span: {freqstr}' - .format(freqstr=freq.freqstr)) + raise ValueError(f'Frequency must be positive, because it ' + f'represents span: {freq.freqstr}') return freq @@ -1614,9 +1613,8 @@ cdef class _Period: return NotImplemented elif op == Py_NE: return NotImplemented - raise TypeError('Cannot compare type {cls} with type {typ}' - .format(cls=type(self).__name__, - typ=type(other).__name__)) + raise TypeError(f'Cannot compare type {type(self).__name__} ' + f'with type {type(other).__name__}') def __hash__(self): return hash((self.ordinal, self.freqstr)) @@ -1634,8 +1632,8 @@ cdef class _Period: if nanos % offset_nanos == 0: ordinal = self.ordinal + (nanos // offset_nanos) return Period(ordinal=ordinal, freq=self.freq) - msg = 'Input cannot be converted to Period(freq={0})' - raise IncompatibleFrequency(msg.format(self.freqstr)) + raise IncompatibleFrequency(f'Input cannot be converted to ' + f'Period(freq={self.freqstr})') elif util.is_offset_object(other): freqstr = other.rule_code base = get_base_alias(freqstr) @@ -1665,9 +1663,8 @@ cdef class _Period: # GH#17983 sname = type(self).__name__ oname = type(other).__name__ - raise TypeError("unsupported operand type(s) for +: '{self}' " - "and '{other}'".format(self=sname, - other=oname)) + raise TypeError(f"unsupported operand type(s) for +: '{sname}' " + f"and '{oname}'") else: # pragma: no cover return NotImplemented elif is_period_object(other): @@ -2218,7 +2215,7 @@ cdef class _Period: def __repr__(self) -> str: base, mult = get_freq_code(self.freq) formatted = period_format(self.ordinal, base) - return "Period('%s', '%s')" % (formatted, self.freqstr) + return f"Period('{formatted}', '{self.freqstr}')" def __str__(self) -> str: """ @@ -2226,7 +2223,7 @@ cdef class _Period: """ base, mult = get_freq_code(self.freq) formatted = period_format(self.ordinal, base) - value = ("%s" % formatted) + value = f"{formatted}" return value def __setstate__(self, state): @@ -2477,9 +2474,8 @@ class Period(_Period): try: freq = Resolution.get_freq(reso) except KeyError: - raise ValueError( - "Invalid frequency or could not infer: {reso}" - .format(reso=reso)) + raise ValueError(f"Invalid frequency or could not " + f"infer: {reso}") elif PyDateTime_Check(value): dt = value diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index fbda5f178e164..b9654fa5bf13f 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -106,11 +106,11 @@ def array_strptime(object[:] values, object fmt, if bad_directive == "\\": bad_directive = "%" del err - raise ValueError("'%s' is a bad directive in format '%s'" % - (bad_directive, fmt)) + raise ValueError(f"'{bad_directive}' is a bad directive " + f"in format '{fmt}'") # IndexError only occurs when the format string is "%" except IndexError: - raise ValueError("stray %% in format '%s'" % fmt) + raise ValueError("stray % in format '{fmt}'") _regex_cache[fmt] = format_regex result = np.empty(n, dtype='M8[ns]') @@ -139,14 +139,13 @@ def array_strptime(object[:] values, object fmt, if is_coerce: iresult[i] = NPY_NAT continue - raise ValueError("time data %r does not match " - "format %r (match)" % (val, fmt)) + raise ValueError(f"time data {repr(val)} does not match " + f"format {repr(fmt)} (match)") if len(val) != found.end(): if is_coerce: iresult[i] = NPY_NAT continue - raise ValueError("unconverted data remains: %s" % - val[found.end():]) + raise ValueError(f"unconverted data remains: {val[found.end():]}") # search else: @@ -155,8 +154,8 @@ def array_strptime(object[:] values, object fmt, if is_coerce: iresult[i] = NPY_NAT continue - raise ValueError("time data %r does not match format " - "%r (search)" % (val, fmt)) + raise ValueError(f"time data {repr(val)} does not match format " + f"{repr(fmt)} (search)") iso_year = -1 year = 1900 @@ -589,8 +588,8 @@ class TimeRE(dict): else: return '' regex = '|'.join(re.escape(stuff) for stuff in to_convert) - regex = '(?P<%s>%s' % (directive, regex) - return '%s)' % regex + regex = f'(?P<{directive}>{regex}' + return f'{regex})' def pattern(self, format): """ @@ -609,11 +608,11 @@ class TimeRE(dict): format = whitespace_replacement.sub(r'\\s+', format) while '%' in format: directive_index = format.index('%') +1 - processed_format = "%s%s%s" % (processed_format, - format[:directive_index -1], - self[format[directive_index]]) + processed_format = (f"{processed_format}" + f"{format[:directive_index -1]}" + f"{self[format[directive_index]]}") format = format[directive_index +1:] - return "%s%s" % (processed_format, format) + return f"{processed_format}{format}" def compile(self, format): """Return a compiled re object for the format string.""" @@ -737,8 +736,7 @@ cdef parse_timezone_directive(str z): z = z[:3] + z[4:] if len(z) > 5: if z[5] != ':': - msg = "Inconsistent use of : in {0}" - raise ValueError(msg.format(z)) + raise ValueError(f"Inconsistent use of : in {z}") z = z[:5] + z[6:] hours = int(z[1:3]) minutes = int(z[3:5]) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 21dbdfbb111ed..066b86fd00425 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -170,7 +170,7 @@ cdef convert_to_timedelta64(object ts, object unit): if ts.astype('int64') == NPY_NAT: return np.timedelta64(NPY_NAT) elif is_timedelta64_object(ts): - ts = ts.astype("m8[{unit}]".format(unit=unit.lower())) + ts = ts.astype(f"m8[{unit.lower()}]") elif is_integer_object(ts): if ts == NPY_NAT: return np.timedelta64(NPY_NAT) @@ -198,8 +198,7 @@ cdef convert_to_timedelta64(object ts, object unit): if PyDelta_Check(ts): ts = np.timedelta64(delta_to_nanoseconds(ts), 'ns') elif not is_timedelta64_object(ts): - raise ValueError("Invalid type for timedelta " - "scalar: {ts_type}".format(ts_type=type(ts))) + raise ValueError(f"Invalid type for timedelta scalar: {type(ts)}") return ts.astype('timedelta64[ns]') @@ -288,7 +287,7 @@ cpdef inline object precision_from_unit(object unit): m = 1L p = 0 else: - raise ValueError("cannot cast unit {unit}".format(unit=unit)) + raise ValueError(f"cannot cast unit {unit}") return m, p @@ -397,8 +396,7 @@ cdef inline int64_t parse_timedelta_string(str ts) except? -1: result += timedelta_as_neg(r, neg) have_hhmmss = 1 else: - raise ValueError("expecting hh:mm:ss format, " - "received: {ts}".format(ts=ts)) + raise ValueError(f"expecting hh:mm:ss format, received: {ts}") unit, number = [], [] @@ -511,7 +509,7 @@ cdef inline timedelta_from_spec(object number, object frac, object unit): unit = 'm' unit = parse_timedelta_unit(unit) except KeyError: - raise ValueError("invalid abbreviation: {unit}".format(unit=unit)) + raise ValueError(f"invalid abbreviation: {unit}") n = ''.join(number) + '.' + ''.join(frac) return cast_from_unit(float(n), unit) @@ -530,8 +528,7 @@ cpdef inline object parse_timedelta_unit(object unit): try: return timedelta_abbrevs[unit.lower()] except (KeyError, AttributeError): - raise ValueError("invalid unit abbreviation: {unit}" - .format(unit=unit)) + raise ValueError(f"invalid unit abbreviation: {unit}") # ---------------------------------------------------------------------- # Timedelta ops utilities @@ -727,8 +724,7 @@ cdef _to_py_int_float(v): return int(v) elif is_float_object(v): return float(v) - raise TypeError("Invalid type {typ}. Must be int or " - "float.".format(typ=type(v))) + raise TypeError(f"Invalid type {type(v)}. Must be int or float.") # Similar to Timestamp/datetime, this is a construction requirement for @@ -773,10 +769,9 @@ cdef class _Timedelta(timedelta): elif op == Py_NE: return True # only allow ==, != ops - raise TypeError('Cannot compare type {cls} with ' - 'type {other}' - .format(cls=type(self).__name__, - other=type(other).__name__)) + raise TypeError(f'Cannot compare type ' + f'{type(self).__name__} with ' + f'type {type(other).__name__}') if util.is_array(other): return PyObject_RichCompare(np.array([self]), other, op) return PyObject_RichCompare(other, self, reverse_ops[op]) @@ -787,10 +782,8 @@ cdef class _Timedelta(timedelta): return False elif op == Py_NE: return True - raise TypeError('Cannot compare type {cls} with ' - 'type {other}' - .format(cls=type(self).__name__, - other=type(other).__name__)) + raise TypeError(f'Cannot compare type {type(self).__name__} with ' + f'type {type(other).__name__}') return cmp_scalar(self.value, ots.value, op) @@ -1143,7 +1136,7 @@ cdef class _Timedelta(timedelta): return fmt.format(**comp_dict) def __repr__(self) -> str: - return "Timedelta('{val}')".format(val=self._repr_base(format='long')) + return f"Timedelta('{self._repr_base(format='long')}')" def __str__(self) -> str: return self._repr_base(format='long') @@ -1189,14 +1182,14 @@ cdef class _Timedelta(timedelta): 'P500DT12H0MS' """ components = self.components - seconds = '{}.{:0>3}{:0>3}{:0>3}'.format(components.seconds, - components.milliseconds, - components.microseconds, - components.nanoseconds) + seconds = (f'{components.seconds}.' + f'{components.milliseconds:0>3}' + f'{components.microseconds:0>3}' + f'{components.nanoseconds:0>3}') # Trim unnecessary 0s, 1.000000000 -> 1 seconds = seconds.rstrip('0').rstrip('.') - tpl = ('P{td.days}DT{td.hours}H{td.minutes}M{seconds}S' - .format(td=components, seconds=seconds)) + tpl = (f'P{components.days}DT{components.hours}' + f'H{components.minutes}M{seconds}S') return tpl @@ -1276,7 +1269,7 @@ class Timedelta(_Timedelta): value = convert_to_timedelta64(value, 'ns') elif is_timedelta64_object(value): if unit is not None: - value = value.astype('timedelta64[{0}]'.format(unit)) + value = value.astype(f'timedelta64[{unit}]') value = value.astype('timedelta64[ns]') elif hasattr(value, 'delta'): value = np.timedelta64(delta_to_nanoseconds(value.delta), 'ns') @@ -1288,9 +1281,8 @@ class Timedelta(_Timedelta): return NaT else: raise ValueError( - "Value must be Timedelta, string, integer, " - "float, timedelta or convertible, not {typ}" - .format(typ=type(value).__name__)) + f"Value must be Timedelta, string, integer, " + f"float, timedelta or convertible, not {type(value).__name__}") if is_timedelta64_object(value): value = value.view('i8') @@ -1485,9 +1477,7 @@ class Timedelta(_Timedelta): else: return self.to_timedelta64() // other - raise TypeError('Invalid dtype {dtype} for ' - '{op}'.format(dtype=other.dtype, - op='__floordiv__')) + raise TypeError(f'Invalid dtype {other.dtype} for __floordiv__') elif is_integer_object(other) or is_float_object(other): return Timedelta(self.value // other, unit='ns') @@ -1530,9 +1520,7 @@ class Timedelta(_Timedelta): """) warnings.warn(msg, FutureWarning) return other // self.value - raise TypeError('Invalid dtype {dtype} for ' - '{op}'.format(dtype=other.dtype, - op='__floordiv__')) + raise TypeError(f'Invalid dtype {other.dtype} for __floordiv__') elif is_float_object(other) and util.is_nan(other): # i.e. np.nan @@ -1555,8 +1543,7 @@ class Timedelta(_Timedelta): if hasattr(other, 'dtype') and other.dtype.kind == 'i': # TODO: Remove this check with backwards-compat shim # for integer / Timedelta is removed. - raise TypeError("Invalid type {dtype} for " - "{op}".format(dtype=other.dtype, op='__mod__')) + raise TypeError(f'Invalid dtype {other.dtype} for __mod__') return self.__rdivmod__(other)[1] def __divmod__(self, other): @@ -1569,8 +1556,7 @@ class Timedelta(_Timedelta): if hasattr(other, 'dtype') and other.dtype.kind == 'i': # TODO: Remove this check with backwards-compat shim # for integer / Timedelta is removed. - raise TypeError("Invalid type {dtype} for " - "{op}".format(dtype=other.dtype, op='__mod__')) + raise TypeError(f'Invalid dtype {other.dtype} for __mod__') div = other // self return div, other - div * self diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 03ed26337d539..1a278f46a4a2b 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -370,8 +370,8 @@ class Timestamp(_Timestamp): if tzinfo is not None: if not PyTZInfo_Check(tzinfo): # tzinfo must be a datetime.tzinfo object, GH#17690 - raise TypeError('tzinfo must be a datetime.tzinfo object, ' - 'not %s' % type(tzinfo)) + raise TypeError(f'tzinfo must be a datetime.tzinfo object, ' + f'not {type(tzinfo)}') elif tz is not None: raise ValueError('Can provide at most one of tz, tzinfo') @@ -946,8 +946,8 @@ default 'raise' def validate(k, v): """ validate integers """ if not is_integer_object(v): - raise ValueError("value must be an integer, received " - "{v} for {k}".format(v=type(v), k=k)) + raise ValueError(f"value must be an integer, received " + f"{type(v)} for {k}") return v if year is not None: @@ -1003,9 +1003,9 @@ default 'raise' base1, base2 = base, "" if self.microsecond != 0: - base1 += "%.3d" % self.nanosecond + base1 += f"{self.nanosecond:03d}" else: - base1 += ".%.9d" % self.nanosecond + base1 += f".{self.nanosecond:09d}" return base1 + base2 diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index bc1fdfae99de9..35ee87e714fa8 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -280,8 +280,8 @@ def infer_tzinfo(start, end): if start is not None and end is not None: tz = start.tzinfo if not tz_compare(tz, end.tzinfo): - msg = 'Inputs must both have the same timezone, {tz1} != {tz2}' - raise AssertionError(msg.format(tz1=tz, tz2=end.tzinfo)) + raise AssertionError(f'Inputs must both have the same timezone, ' + f'{tz} != {end.tzinfo}') elif start is not None: tz = start.tzinfo elif end is not None: diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index dd0c6fc75b06f..b368f0fde3edc 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -175,8 +175,8 @@ timedelta-like} if trans_idx.size == 1: stamp = _render_tstamp(vals[trans_idx]) raise pytz.AmbiguousTimeError( - "Cannot infer dst time from %s as there " - "are no repeated times".format(stamp)) + f"Cannot infer dst time from {stamp} as there " + f"are no repeated times") # Split the array into contiguous chunks (where the difference between # indices is 1). These are effectively dst transitions in different # years which is useful for checking that there is not an ambiguous @@ -200,8 +200,8 @@ timedelta-like} switch_idx = (delta <= 0).nonzero()[0] if switch_idx.size > 1: raise pytz.AmbiguousTimeError( - "There are %i dst switches when " - "there should only be 1.".format(switch_idx.size)) + f"There are {switch_idx.size} dst switches when " + f"there should only be 1.") switch_idx = switch_idx[0] + 1 # Pull the only index and adjust a_idx = grp[:switch_idx] @@ -230,8 +230,8 @@ timedelta-like} else: stamp = _render_tstamp(val) raise pytz.AmbiguousTimeError( - "Cannot infer dst time from %r, try using the " - "'ambiguous' argument".format(stamp)) + f"Cannot infer dst time from {stamp}, try using the " + f"'ambiguous' argument") elif left != NPY_NAT: result[i] = left elif right != NPY_NAT: @@ -246,8 +246,8 @@ timedelta-like} # time if -1 < shift_delta + remaining_mins < HOURS_NS: raise ValueError( - "The provided timedelta will relocalize on a " - "nonexistent time: {}".format(nonexistent) + f"The provided timedelta will relocalize on a " + f"nonexistent time: {nonexistent}" ) new_local = val + shift_delta elif shift_forward: