Skip to content

Commit 191e993

Browse files
pgansslevstinner
authored andcommitted
bpo-31222: Make (datetime|date|time).replace return subclass type in Pure Python (python#4176)
1 parent 72fa301 commit 191e993

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

Lib/datetime.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -828,7 +828,7 @@ def replace(self, year=None, month=None, day=None):
828828
month = self._month
829829
if day is None:
830830
day = self._day
831-
return date(year, month, day)
831+
return type(self)(year, month, day)
832832

833833
# Comparisons of date objects with other.
834834

@@ -1316,7 +1316,7 @@ def replace(self, hour=None, minute=None, second=None, microsecond=None,
13161316
tzinfo = self.tzinfo
13171317
if fold is None:
13181318
fold = self._fold
1319-
return time(hour, minute, second, microsecond, tzinfo, fold=fold)
1319+
return type(self)(hour, minute, second, microsecond, tzinfo, fold=fold)
13201320

13211321
# Pickle support.
13221322

@@ -1597,7 +1597,7 @@ def replace(self, year=None, month=None, day=None, hour=None,
15971597
tzinfo = self.tzinfo
15981598
if fold is None:
15991599
fold = self.fold
1600-
return datetime(year, month, day, hour, minute, second,
1600+
return type(self)(year, month, day, hour, minute, second,
16011601
microsecond, tzinfo, fold=fold)
16021602

16031603
def _local_timezone(self):

Lib/test/datetimetester.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1520,6 +1520,13 @@ def test_replace(self):
15201520
base = cls(2000, 2, 29)
15211521
self.assertRaises(ValueError, base.replace, year=2001)
15221522

1523+
def test_subclass_replace(self):
1524+
class DateSubclass(self.theclass):
1525+
pass
1526+
1527+
dt = DateSubclass(2012, 1, 1)
1528+
self.assertIs(type(dt.replace(year=2013)), DateSubclass)
1529+
15231530
def test_subclass_date(self):
15241531

15251532
class C(self.theclass):
@@ -2626,6 +2633,13 @@ def test_replace(self):
26262633
self.assertRaises(ValueError, base.replace, second=100)
26272634
self.assertRaises(ValueError, base.replace, microsecond=1000000)
26282635

2636+
def test_subclass_replace(self):
2637+
class TimeSubclass(self.theclass):
2638+
pass
2639+
2640+
ctime = TimeSubclass(12, 30)
2641+
self.assertIs(type(ctime.replace(hour=10)), TimeSubclass)
2642+
26292643
def test_subclass_time(self):
26302644

26312645
class C(self.theclass):

0 commit comments

Comments
 (0)