Add floordiv to pathlib.Path for strict append

Hi! After a recent bug in a project, I felt it would be helpful to have Path // str operate as a “strict” alternative, which would raise a ValueError if the str included the separator in it.

It could be as simple as:

diff --git a/Lib/ b/Lib/
index 911b774b56..7739860982 100644
--- a/Lib/
+++ b/Lib/
@@ -903,6 +903,15 @@ class PurePath(object):
     def __rtruediv__(self, key):
         return self._from_parts([key] + self._parts)
+    def __floordiv__(self, key):
+        """A strict verison of div that does not allow separators in the value.
+        This is to prevent accidentally adding sub-directories to a path.
+        """
+        f = self._flavour
+        if f.sep in key:
+            raise ValueError(f'Found {f.sep} in path value: {key}')
+        return self.__truediv__(self, key)
     def parent(self):
         """The logical parent of the path."""

Although, perhaps it ought check if key is a string… Then again, if you’re using this, you may reasonably be expected to ensure yourself to only use it with strings.

Thanks for the idea but I don’t think this is worth the overhead of needing to remember what // represents for paths since it’s non-obvious. Basically tests should cover this use-case.


A proper named method, like path.join_segment or something, seems more likely to find support. Python style tends to prefer words over operators, except for the very most common cases.

1 Like