From 39dcdc99c081d1f5d128cebad0fdddbc84d6fefa Mon Sep 17 00:00:00 2001 From: barneygale Date: Wed, 24 May 2023 22:51:16 +0100 Subject: [PATCH] GH-104898: Add __slots__ to os.PathLike --- Lib/os.py | 2 ++ Lib/pathlib.py | 6 +----- Lib/test/test_os.py | 6 ++++++ .../Library/2023-05-24-22-50-21.gh-issue-104898.UbT2S4.rst | 1 + 4 files changed, 10 insertions(+), 5 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2023-05-24-22-50-21.gh-issue-104898.UbT2S4.rst diff --git a/Lib/os.py b/Lib/os.py index 598c9e502301f7..31b957f13215d5 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -1079,6 +1079,8 @@ class PathLike(abc.ABC): """Abstract base class for implementing the file system path protocol.""" + __slots__ = () + @abc.abstractmethod def __fspath__(self): """Return the file system path representation of the object.""" diff --git a/Lib/pathlib.py b/Lib/pathlib.py index 3a7a1241ba77f6..fb78939dcc31ba 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -233,7 +233,7 @@ def __repr__(self): return "<{}.parents>".format(type(self._path).__name__) -class PurePath(object): +class PurePath(os.PathLike): """Base class for manipulating paths without I/O. PurePath represents a filesystem path and offers operations which @@ -707,10 +707,6 @@ def match(self, path_pattern, *, case_sensitive=None): return False return True -# Can't subclass os.PathLike from PurePath and keep the constructor -# optimizations in PurePath.__slots__. -os.PathLike.register(PurePath) - class PurePosixPath(PurePath): """PurePath subclass for non-Windows systems. diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index 584cc05ca82a55..c6810c07ae09d8 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -4640,6 +4640,12 @@ class A(os.PathLike): def test_pathlike_class_getitem(self): self.assertIsInstance(os.PathLike[bytes], types.GenericAlias) + def test_pathlike_subclass_slots(self): + class A(os.PathLike): + __slots__ = () + def __fspath__(self): + return '' + self.assertFalse(hasattr(A(), '__dict__')) class TimesTests(unittest.TestCase): def test_times(self): diff --git a/Misc/NEWS.d/next/Library/2023-05-24-22-50-21.gh-issue-104898.UbT2S4.rst b/Misc/NEWS.d/next/Library/2023-05-24-22-50-21.gh-issue-104898.UbT2S4.rst new file mode 100644 index 00000000000000..e596ab36f5c729 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-05-24-22-50-21.gh-issue-104898.UbT2S4.rst @@ -0,0 +1 @@ +Add missing :attr:`~object.__slots__` to :class:`os.PathLike`.