Skip to content

Commit b0cb2f3

Browse files
author
MomIsBestFriend
committed
F-strings and repr
1 parent cb05112 commit b0cb2f3

File tree

5 files changed

+138
-224
lines changed

5 files changed

+138
-224
lines changed

pandas/tests/tseries/offsets/test_fiscal.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,9 @@ def test_get_offset():
7979

8080
for name, expected in pairs:
8181
offset = get_offset(name)
82-
assert (
83-
offset == expected
84-
), "Expected {name!r} to yield {expected!r} (actual: {offset!r})".format(
85-
name=name, expected=expected, offset=offset
82+
assert offset == expected, (
83+
f"Expected {repr(name)} to yield {repr(expected)} "
84+
f"(actual: {repr(offset)})"
8685
)
8786

8887

pandas/tests/tseries/offsets/test_offsets.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -3969,10 +3969,9 @@ def test_get_offset():
39693969

39703970
for name, expected in pairs:
39713971
offset = get_offset(name)
3972-
assert (
3973-
offset == expected
3974-
), "Expected {name!r} to yield {expected!r} (actual: {offset!r})".format(
3975-
name=name, expected=expected, offset=offset
3972+
assert offset == expected, (
3973+
f"Expected {repr(name)} to yield {repr(expected)} "
3974+
f"(actual: {repr(offset)})"
39763975
)
39773976

39783977

@@ -4170,9 +4169,9 @@ def _test_offset(self, offset_name, offset_n, tstart, expected_utc_offset):
41704169

41714170
def _make_timestamp(self, string, hrs_offset, tz):
41724171
if hrs_offset >= 0:
4173-
offset_string = "{hrs:02d}00".format(hrs=hrs_offset)
4172+
offset_string = f"{hrs_offset:02}00"
41744173
else:
4175-
offset_string = "-{hrs:02d}00".format(hrs=-1 * hrs_offset)
4174+
offset_string = f"-{(hrs_offset * -1):02}00"
41764175
return Timestamp(string + offset_string).tz_convert(tz)
41774176

41784177
def test_springforward_plural(self):

pandas/tseries/offsets.py

+38-69
Original file line numberDiff line numberDiff line change
@@ -359,8 +359,8 @@ def apply_index(self, i):
359359
kwd = set(kwds) - relativedelta_fast
360360
raise NotImplementedError(
361361
"DateOffset with relativedelta "
362-
"keyword(s) {kwd} not able to be "
363-
"applied vectorized".format(kwd=kwd)
362+
f"keyword(s) {kwd} not able to be "
363+
"applied vectorized"
364364
)
365365

366366
def isAnchored(self):
@@ -379,7 +379,7 @@ def _repr_attrs(self):
379379
continue
380380
elif attr not in exclude:
381381
value = getattr(self, attr)
382-
attrs.append("{attr}={value}".format(attr=attr, value=value))
382+
attrs.append(f"{attr}={value}")
383383

384384
out = ""
385385
if attrs:
@@ -449,7 +449,7 @@ def freqstr(self):
449449
return repr(self)
450450

451451
if self.n != 1:
452-
fstr = "{n}{code}".format(n=self.n, code=code)
452+
fstr = f"{self.n}{code}"
453453
else:
454454
fstr = code
455455

@@ -467,15 +467,15 @@ def _offset_str(self):
467467

468468
@property
469469
def nanos(self):
470-
raise ValueError("{name} is a non-fixed frequency".format(name=self))
470+
raise ValueError(f"{self} is a non-fixed frequency")
471471

472472

473473
class SingleConstructorOffset(DateOffset):
474474
@classmethod
475475
def _from_name(cls, suffix=None):
476476
# default _from_name calls cls with no args
477477
if suffix:
478-
raise ValueError("Bad freq suffix {suffix}".format(suffix=suffix))
478+
raise ValueError(f"Bad freq suffix {suffix}")
479479
return cls()
480480

481481

@@ -513,7 +513,7 @@ def offset(self):
513513

514514
def _repr_attrs(self):
515515
if self.offset:
516-
attrs = ["offset={offset!r}".format(offset=self.offset)]
516+
attrs = [f"offset={repr(self.offset)}"]
517517
else:
518518
attrs = None
519519
out = ""
@@ -966,10 +966,10 @@ def _onOffset(self, dt):
966966
def _repr_attrs(self):
967967
out = super()._repr_attrs()
968968
hours = ",".join(
969-
"{}-{}".format(st.strftime("%H:%M"), en.strftime("%H:%M"))
969+
f'{st.strftime("%H:%M")}-{en.strftime("%H:%M")}'
970970
for st, en in zip(self.start, self.end)
971971
)
972-
attrs = ["{prefix}={hours}".format(prefix=self._prefix, hours=hours)]
972+
attrs = [f"{self._prefix}={hours}"]
973973
out += ": " + ", ".join(attrs)
974974
return out
975975

@@ -1113,7 +1113,7 @@ def name(self):
11131113
return self.rule_code
11141114
else:
11151115
month = ccalendar.MONTH_ALIASES[self.n]
1116-
return "{code}-{month}".format(code=self.rule_code, month=month)
1116+
return f"{self.code_rule}-{month}"
11171117

11181118
def onOffset(self, dt):
11191119
if self.normalize and not _is_normalized(dt):
@@ -1296,9 +1296,10 @@ def __init__(self, n=1, normalize=False, day_of_month=None):
12961296
else:
12971297
object.__setattr__(self, "day_of_month", int(day_of_month))
12981298
if not self._min_day_of_month <= self.day_of_month <= 27:
1299-
msg = "day_of_month must be {min}<=day_of_month<=27, got {day}"
13001299
raise ValueError(
1301-
msg.format(min=self._min_day_of_month, day=self.day_of_month)
1300+
"day_of_month must be "
1301+
f"{self._min_day_of_month}<=day_of_month<=27, "
1302+
f"got {self.day_of_month}"
13021303
)
13031304

13041305
@classmethod
@@ -1307,7 +1308,7 @@ def _from_name(cls, suffix=None):
13071308

13081309
@property
13091310
def rule_code(self):
1310-
suffix = "-{day_of_month}".format(day_of_month=self.day_of_month)
1311+
suffix = f"-{self.day_of_month}"
13111312
return self._prefix + suffix
13121313

13131314
@apply_wraps
@@ -1527,9 +1528,7 @@ def __init__(self, n=1, normalize=False, weekday=None):
15271528

15281529
if self.weekday is not None:
15291530
if self.weekday < 0 or self.weekday > 6:
1530-
raise ValueError(
1531-
"Day must be 0<=day<=6, got {day}".format(day=self.weekday)
1532-
)
1531+
raise ValueError(f"Day must be 0<=day<=6, got {self.weekday}")
15331532

15341533
def isAnchored(self):
15351534
return self.n == 1 and self.weekday is not None
@@ -1541,9 +1540,7 @@ def apply(self, other):
15411540

15421541
if not isinstance(other, datetime):
15431542
raise TypeError(
1544-
"Cannot add {typ} to {cls}".format(
1545-
typ=type(other).__name__, cls=type(self).__name__
1546-
)
1543+
f"Cannot add {type(other).__name__} to {type(self).__name__}"
15471544
)
15481545

15491546
k = self.n
@@ -1621,7 +1618,7 @@ def rule_code(self):
16211618
suffix = ""
16221619
if self.weekday is not None:
16231620
weekday = ccalendar.int_to_weekday[self.weekday]
1624-
suffix = "-{weekday}".format(weekday=weekday)
1621+
suffix = f"-{weekday}"
16251622
return self._prefix + suffix
16261623

16271624
@classmethod
@@ -1690,13 +1687,9 @@ def __init__(self, n=1, normalize=False, week=0, weekday=0):
16901687
object.__setattr__(self, "week", week)
16911688

16921689
if self.weekday < 0 or self.weekday > 6:
1693-
raise ValueError(
1694-
"Day must be 0<=day<=6, got {day}".format(day=self.weekday)
1695-
)
1690+
raise ValueError(f"Day must be 0<=day<=6, got {self.weekday}")
16961691
if self.week < 0 or self.week > 3:
1697-
raise ValueError(
1698-
"Week must be 0<=week<=3, got {week}".format(week=self.week)
1699-
)
1692+
raise ValueError(f"Week must be 0<=week<=3, got {self.week}")
17001693

17011694
def _get_offset_day(self, other):
17021695
"""
@@ -1719,16 +1712,12 @@ def _get_offset_day(self, other):
17191712
@property
17201713
def rule_code(self):
17211714
weekday = ccalendar.int_to_weekday.get(self.weekday, "")
1722-
return "{prefix}-{week}{weekday}".format(
1723-
prefix=self._prefix, week=self.week + 1, weekday=weekday
1724-
)
1715+
return f"{self._prefix}-{self.week + 1}{weekday}"
17251716

17261717
@classmethod
17271718
def _from_name(cls, suffix=None):
17281719
if not suffix:
1729-
raise ValueError(
1730-
"Prefix {prefix!r} requires a suffix.".format(prefix=cls._prefix)
1731-
)
1720+
raise ValueError(f"Prefix {repr(cls._prefix)} requires a suffix.")
17321721
# TODO: handle n here...
17331722
# only one digit weeks (1 --> week 0, 2 --> week 1, etc.)
17341723
week = int(suffix[0]) - 1
@@ -1768,9 +1757,7 @@ def __init__(self, n=1, normalize=False, weekday=0):
17681757
raise ValueError("N cannot be 0")
17691758

17701759
if self.weekday < 0 or self.weekday > 6:
1771-
raise ValueError(
1772-
"Day must be 0<=day<=6, got {day}".format(day=self.weekday)
1773-
)
1760+
raise ValueError(f"Day must be 0<=day<=6, got {self.weekday}")
17741761

17751762
def _get_offset_day(self, other):
17761763
"""
@@ -1794,14 +1781,12 @@ def _get_offset_day(self, other):
17941781
@property
17951782
def rule_code(self):
17961783
weekday = ccalendar.int_to_weekday.get(self.weekday, "")
1797-
return "{prefix}-{weekday}".format(prefix=self._prefix, weekday=weekday)
1784+
return f"{self._prefix}-{weekday}"
17981785

17991786
@classmethod
18001787
def _from_name(cls, suffix=None):
18011788
if not suffix:
1802-
raise ValueError(
1803-
"Prefix {prefix!r} requires a suffix.".format(prefix=cls._prefix)
1804-
)
1789+
raise ValueError(f"Prefix {repr(cls._prefix)} requires a suffix.")
18051790
# TODO: handle n here...
18061791
weekday = ccalendar.weekday_to_int[suffix]
18071792
return cls(weekday=weekday)
@@ -1847,7 +1832,7 @@ def _from_name(cls, suffix=None):
18471832
@property
18481833
def rule_code(self):
18491834
month = ccalendar.MONTH_ALIASES[self.startingMonth]
1850-
return "{prefix}-{month}".format(prefix=self._prefix, month=month)
1835+
return f"{self._prefix}-{month}"
18511836

18521837
@apply_wraps
18531838
def apply(self, other):
@@ -1990,7 +1975,7 @@ def _from_name(cls, suffix=None):
19901975
@property
19911976
def rule_code(self):
19921977
month = ccalendar.MONTH_ALIASES[self.month]
1993-
return "{prefix}-{month}".format(prefix=self._prefix, month=month)
1978+
return f"{self._prefix}-{month}"
19941979

19951980

19961981
class BYearEnd(YearOffset):
@@ -2104,9 +2089,7 @@ def __init__(
21042089
raise ValueError("N cannot be 0")
21052090

21062091
if self.variation not in ["nearest", "last"]:
2107-
raise ValueError(
2108-
"{variation} is not a valid variation".format(variation=self.variation)
2109-
)
2092+
raise ValueError(f"{self.variation} is not a valid variation")
21102093

21112094
def isAnchored(self):
21122095
return (
@@ -2211,7 +2194,7 @@ def get_year_end(self, dt):
22112194
def rule_code(self):
22122195
prefix = self._prefix
22132196
suffix = self.get_rule_code_suffix()
2214-
return "{prefix}-{suffix}".format(prefix=prefix, suffix=suffix)
2197+
return f"{prefix}-{suffix}"
22152198

22162199
def _get_suffix_prefix(self):
22172200
if self.variation == "nearest":
@@ -2223,9 +2206,7 @@ def get_rule_code_suffix(self):
22232206
prefix = self._get_suffix_prefix()
22242207
month = ccalendar.MONTH_ALIASES[self.startingMonth]
22252208
weekday = ccalendar.int_to_weekday[self.weekday]
2226-
return "{prefix}-{month}-{weekday}".format(
2227-
prefix=prefix, month=month, weekday=weekday
2228-
)
2209+
return f"{prefix}-{month}-{weekday}"
22292210

22302211
@classmethod
22312212
def _parse_suffix(cls, varion_code, startingMonth_code, weekday_code):
@@ -2234,9 +2215,7 @@ def _parse_suffix(cls, varion_code, startingMonth_code, weekday_code):
22342215
elif varion_code == "L":
22352216
variation = "last"
22362217
else:
2237-
raise ValueError(
2238-
"Unable to parse varion_code: {code}".format(code=varion_code)
2239-
)
2218+
raise ValueError(f"Unable to parse varion_code: {varion_code}")
22402219

22412220
startingMonth = ccalendar.MONTH_TO_CAL_NUM[startingMonth_code]
22422221
weekday = ccalendar.weekday_to_int[weekday_code]
@@ -2461,9 +2440,7 @@ def onOffset(self, dt):
24612440
def rule_code(self):
24622441
suffix = self._offset.get_rule_code_suffix()
24632442
qtr = self.qtr_with_extra_week
2464-
return "{prefix}-{suffix}-{qtr}".format(
2465-
prefix=self._prefix, suffix=suffix, qtr=qtr
2466-
)
2443+
return f"{self._prefix}-{suffix}-{qtr}"
24672444

24682445
@classmethod
24692446
def _from_name(cls, *args):
@@ -2532,12 +2509,11 @@ def f(self, other):
25322509
except AttributeError:
25332510
# comparing with a non-Tick object
25342511
raise TypeError(
2535-
"Invalid comparison between {cls} and {typ}".format(
2536-
cls=type(self).__name__, typ=type(other).__name__
2537-
)
2512+
f"Invalid comparison between {type(self).__name__} "
2513+
f"and {type(other).__name__}"
25382514
)
25392515

2540-
f.__name__ = "__{opname}__".format(opname=op.__name__)
2516+
f.__name__ = f"__{op.__name__}__"
25412517
return f
25422518

25432519

@@ -2572,8 +2548,7 @@ def __add__(self, other):
25722548
return NotImplemented
25732549
except OverflowError:
25742550
raise OverflowError(
2575-
"the add operation between {self} and {other} "
2576-
"will overflow".format(self=self, other=other)
2551+
f"the add operation between {self} and {other} will overflow"
25772552
)
25782553

25792554
def __eq__(self, other) -> bool:
@@ -2645,9 +2620,7 @@ def apply(self, other):
26452620
elif isinstance(other, type(self)):
26462621
return type(self)(self.n + other.n)
26472622

2648-
raise ApplyTypeError(
2649-
"Unhandled type: {type_str}".format(type_str=type(other).__name__)
2650-
)
2623+
raise ApplyTypeError(f"Unhandled type: {type(other).__name__}")
26512624

26522625
def isAnchored(self):
26532626
return False
@@ -2783,9 +2756,7 @@ def generate_range(start=None, end=None, periods=None, offset=BDay()):
27832756
# faster than cur + offset
27842757
next_date = offset.apply(cur)
27852758
if next_date <= cur:
2786-
raise ValueError(
2787-
"Offset {offset} did not increment date".format(offset=offset)
2788-
)
2759+
raise ValueError(f"Offset {offset} did not increment date")
27892760
cur = next_date
27902761
else:
27912762
while cur >= end:
@@ -2799,9 +2770,7 @@ def generate_range(start=None, end=None, periods=None, offset=BDay()):
27992770
# faster than cur + offset
28002771
next_date = offset.apply(cur)
28012772
if next_date >= cur:
2802-
raise ValueError(
2803-
"Offset {offset} did not decrement date".format(offset=offset)
2804-
)
2773+
raise ValueError(f"Offset {offset} did not decrement date")
28052774
cur = next_date
28062775

28072776

0 commit comments

Comments
 (0)