Skip to content
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

bpo-34775: Return NotImplemented in PurePath division. #9509

Merged
merged 6 commits into from
Aug 8, 2019
Merged
Show file tree
Hide file tree
Changes from 3 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
10 changes: 8 additions & 2 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -889,10 +889,16 @@ def joinpath(self, *args):
return self._make_child(args)

def __truediv__(self, key):
return self._make_child((key,))
try:
return self._make_child((key,))
except TypeError:
return NotImplemented

def __rtruediv__(self, key):
return self._from_parts([key] + self._parts)
try:
return self._from_parts([key] + self._parts)
except TypeError:
return NotImplemented

@property
def parent(self):
Expand Down
39 changes: 39 additions & 0 deletions Lib/test/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -2298,5 +2298,44 @@ def check():
check()


class CompatiblePathTest(unittest.TestCase):
"""
Test that a type can be made compatible with PurePath
derivatives by implementing division operator overloads.
"""

class CompatPath:
"""
Simple class to store a string and uses combine that
aiudirog marked this conversation as resolved.
Show resolved Hide resolved
string with other object's string values via division.
"""
def __init__(self, string):
self.string = string

def __truediv__(self, other):
return type(self)(f"{self.string}/{other}")

def __rtruediv__(self, other):
return type(self)(f"{other}/{self.string}")

def test_truediv(self):
result = pathlib.PurePath("test") / self.CompatPath("right")
self.assertIsInstance(result, self.CompatPath)
self.assertEqual(result.string, "test/right")

with self.assertRaises(TypeError):
# Verify improper operations still raise a TypeError
pathlib.PurePath("test") / 10

def test_rtruediv(self):
result = self.CompatPath("left") / pathlib.PurePath("test")
self.assertIsInstance(result, self.CompatPath)
self.assertEqual(result.string, "left/test")

with self.assertRaises(TypeError):
# Verify improper operations still raise a TypeError
10 / pathlib.PurePath("test")


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Division handling of PurePath now returns NotImplemented instead of raising
a TypeError when passed something other than an instance of str or PurePath.
aiudirog marked this conversation as resolved.
Show resolved Hide resolved