bpo-34775: Return NotImplemented in PurePath division. (GH-9509) · python/cpython@4c69be2 (original) (raw)

3 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -907,10 +907,16 @@ def joinpath(self, *args):
907 907 return self._make_child(args)
908 908
909 909 def __truediv__(self, key):
910 -return self._make_child((key,))
910 +try:
911 +return self._make_child((key,))
912 +except TypeError:
913 +return NotImplemented
911 914
912 915 def __rtruediv__(self, key):
913 -return self._from_parts([key] + self._parts)
916 +try:
917 +return self._from_parts([key] + self._parts)
918 +except TypeError:
919 +return NotImplemented
914 920
915 921 @property
916 922 def parent(self):
Original file line number Diff line number Diff line change
@@ -2329,5 +2329,46 @@ def check():
2329 2329 check()
2330 2330
2331 2331
2332 +class CompatiblePathTest(unittest.TestCase):
2333 +"""
2334 + Test that a type can be made compatible with PurePath
2335 + derivatives by implementing division operator overloads.
2336 + """
2337 +
2338 +class CompatPath:
2339 +"""
2340 + Minimum viable class to test PurePath compatibility.
2341 + Simply uses the division operator to join a given
2342 + string and the string value of another object with
2343 + a forward slash.
2344 + """
2345 +def __init__(self, string):
2346 +self.string = string
2347 +
2348 +def __truediv__(self, other):
2349 +return type(self)(f"{self.string}/{other}")
2350 +
2351 +def __rtruediv__(self, other):
2352 +return type(self)(f"{other}/{self.string}")
2353 +
2354 +def test_truediv(self):
2355 +result = pathlib.PurePath("test") / self.CompatPath("right")
2356 +self.assertIsInstance(result, self.CompatPath)
2357 +self.assertEqual(result.string, "test/right")
2358 +
2359 +with self.assertRaises(TypeError):
2360 +# Verify improper operations still raise a TypeError
2361 +pathlib.PurePath("test") / 10
2362 +
2363 +def test_rtruediv(self):
2364 +result = self.CompatPath("left") / pathlib.PurePath("test")
2365 +self.assertIsInstance(result, self.CompatPath)
2366 +self.assertEqual(result.string, "left/test")
2367 +
2368 +with self.assertRaises(TypeError):
2369 +# Verify improper operations still raise a TypeError
2370 +10 / pathlib.PurePath("test")
2371 +
2372 +
2332 2373 if __name__ == "__main__":
2333 2374 unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1 +Division handling of PurePath now returns NotImplemented instead of raising
2 +a TypeError when passed something other than an instance of str or PurePath.
3 +Patch by Roger Aiudi.