Skip to content

Convert to fstring #30094

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pandas/_libs/tslibs/frequencies.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ opattern = re.compile(
r'([+\-]?\d*|[+\-]?\d*\.\d*)\s*([A-Za-z]+([\-][\dA-Za-z\-]+)?)'
)

INVALID_FREQ_ERR_MSG = "Invalid frequency: {0}"
INVALID_FREQ_ERR_MSG = lambda arg: f"Invalid frequency: {arg}"

# ---------------------------------------------------------------------
# Period codes
Expand Down Expand Up @@ -223,7 +223,7 @@ cpdef _period_str_to_code(str freqstr):
try:
return _period_code_map[freqstr]
except KeyError:
raise ValueError(INVALID_FREQ_ERR_MSG.format(freqstr))
raise ValueError(INVALID_FREQ_ERR_MSG(freqstr))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a typo?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,
In order to converting str.format() to f string I changed INVALID_FREQ_ERR_MSG definition from predefined string to lambda function. Now error message is defined in one place and is callable without .format().

Current definition:
INVALID_FREQ_ERR_MSG = lambda arg: f"Invalid frequency {arg}"

So now message is called as a function:
INVALID_FREQ_ERR_MSG(arg_str)



cpdef str get_freq_str(base, mult=1):
Expand Down
40 changes: 20 additions & 20 deletions pandas/_libs/tslibs/period.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1209,8 +1209,7 @@ def period_format(int64_t value, int freq, object fmt=None):
elif freq_group == 4000: # WK
left = period_asfreq(value, freq, 6000, 0)
right = period_asfreq(value, freq, 6000, 1)
return '%s/%s' % (period_format(left, 6000),
period_format(right, 6000))
return f"{period_format(left, 6000)}/{period_format(right, 6000)}"
elif (freq_group == 5000 # BUS
or freq_group == 6000): # DAY
fmt = b'%Y-%m-%d'
Expand All @@ -1227,7 +1226,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(f'Unknown freq: {freq}')
raise ValueError(f"Unknown freq: {freq}")

return _period_strftime(value, freq, fmt)

Expand Down Expand Up @@ -1275,15 +1274,15 @@ cdef object _period_strftime(int64_t value, int freq, object fmt):
if i == 0:
repl = str(quarter)
elif i == 1: # %f, 2-digit year
repl = f'{(year % 100):02d}'
repl = f"{(year % 100):02d}"
elif i == 2:
repl = str(year)
elif i == 3:
repl = f'{(value % 1_000):03d}'
repl = f"{(value % 1_000):03d}"
elif i == 4:
repl = f'{(value % 1_000_000):06d}'
repl = f"{(value % 1_000_000):06d}"
elif i == 5:
repl = f'{(value % 1_000_000_000):09d}'
repl = f"{(value % 1_000_000_000):09d}"

result = result.replace(str_extra_fmts[i], repl)

Expand Down Expand Up @@ -1391,7 +1390,7 @@ def get_period_field_arr(int code, int64_t[:] arr, int freq):

func = _get_accessor_func(code)
if func is NULL:
raise ValueError(f'Unrecognized period code: {code}')
raise ValueError(f"Unrecognized period code: {code}")

sz = len(arr)
out = np.empty(sz, dtype=np.int64)
Expand Down Expand Up @@ -1455,7 +1454,7 @@ def extract_ordinals(ndarray[object] values, freq):
ordinals[i] = p.ordinal

if p.freqstr != freqstr:
msg = DIFFERENT_FREQ.format(cls="PeriodIndex",
msg = DIFFERENT_FREQ(cls="PeriodIndex",
own_freq=freqstr,
other_freq=p.freqstr)
raise IncompatibleFrequency(msg)
Expand Down Expand Up @@ -1549,8 +1548,9 @@ cdef int64_t[:] localize_dt64arr_to_period(int64_t[:] stamps,
return result


DIFFERENT_FREQ = ("Input has different freq={other_freq} "
"from {cls}(freq={own_freq})")

DIFFERENT_FREQ = lambda other_freq, cls, own_freq: f"Input has different freq={other_freq} " \
f"from {cls}(freq={own_freq})"


class IncompatibleFrequency(ValueError):
Expand Down Expand Up @@ -1578,8 +1578,8 @@ cdef class _Period:
freq = to_offset(freq)

if freq.n <= 0:
raise ValueError(f'Frequency must be positive, because it '
f'represents span: {freq.freqstr}')
raise ValueError(f"Frequency must be positive, because it "
f"represents span: {freq.freqstr}")

return freq

Expand All @@ -1598,7 +1598,7 @@ cdef class _Period:
def __richcmp__(self, other, op):
if is_period_object(other):
if other.freq != self.freq:
msg = DIFFERENT_FREQ.format(cls=type(self).__name__,
msg = DIFFERENT_FREQ(cls=type(self).__name__,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need an f string?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same deal as abowe in frequencies.pyx file. DIFFERENT_FREQ is now a lambda function

own_freq=self.freqstr,
other_freq=other.freqstr)
raise IncompatibleFrequency(msg)
Expand All @@ -1613,8 +1613,8 @@ cdef class _Period:
return NotImplemented
elif op == Py_NE:
return NotImplemented
raise TypeError(f'Cannot compare type {type(self).__name__} '
f'with type {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))
Expand All @@ -1632,15 +1632,15 @@ cdef class _Period:
if nanos % offset_nanos == 0:
ordinal = self.ordinal + (nanos // offset_nanos)
return Period(ordinal=ordinal, freq=self.freq)
raise IncompatibleFrequency(f'Input cannot be converted to '
f'Period(freq={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)
if base == self.freq.rule_code:
ordinal = self.ordinal + other.n
return Period(ordinal=ordinal, freq=self.freq)
msg = DIFFERENT_FREQ.format(cls=type(self).__name__,
msg = DIFFERENT_FREQ(cls=type(self).__name__,
own_freq=self.freqstr,
other_freq=other.freqstr)
raise IncompatibleFrequency(msg)
Expand Down Expand Up @@ -1684,7 +1684,7 @@ cdef class _Period:
return Period(ordinal=ordinal, freq=self.freq)
elif is_period_object(other):
if other.freq != self.freq:
msg = DIFFERENT_FREQ.format(cls=type(self).__name__,
msg = DIFFERENT_FREQ(cls=type(self).__name__,
own_freq=self.freqstr,
other_freq=other.freqstr)
raise IncompatibleFrequency(msg)
Expand Down
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ cdef inline int64_t parse_iso_format_string(object ts) except? -1:
bint have_dot = 0, have_value = 0, neg = 0
list number = [], unit = []

err_msg = "Invalid ISO 8601 Duration format - {}".format(ts)
err_msg = f"Invalid ISO 8601 Duration format - {ts}"

for c in ts:
# number (ascii codes)
Expand Down
8 changes: 4 additions & 4 deletions pandas/tseries/frequencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def to_offset(freq) -> Optional[DateOffset]:
else:
delta = delta + offset
except ValueError:
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG(freq))

else:
delta = None
Expand Down Expand Up @@ -173,10 +173,10 @@ def to_offset(freq) -> Optional[DateOffset]:
else:
delta = delta + offset
except (ValueError, TypeError):
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG(freq))

if delta is None:
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG(freq))

return delta

Expand Down Expand Up @@ -205,7 +205,7 @@ def get_offset(name: str) -> DateOffset:
offset = klass._from_name(*split[1:])
except (ValueError, TypeError, KeyError):
# bad prefix or suffix
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(name))
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG(name))
# cache
_offset_map[name] = offset

Expand Down