[issue41109] subclasses of pathlib.PurePosixPath never call __init__ or __new__

Louis-Vincent Boudreault report at bugs.python.org
Sat Aug 8 09:47:37 EDT 2020


Louis-Vincent Boudreault <lv.boudreault95 at gmail.com> added the comment:

Path.__new__ should not call _from_parts because it breaks the specialization by directly using object.__new__.
This is why `_from_parts` has to be duplicated in each subclass's `__new__`.

My suggestion (first draft) is to do the parsing of arguments inside an `__init__` in the Path class hierarchy
and deprecate  `_from_parts`.

```
class PurePath:
   
     def __new__(cls, *args):
         if cls is PurePath:
             cls = PureWindowsPath if os.name == 'nt' else PurePosixPath
         super().__new__(cls, *args) # Here we remove call to from_parts

     def __init__(self, *args):
         # We should have an __init__ in the hierarchy.
         drv, root, parts = self._parse_args(args)  # this would get the proper _flavour.
         self._drv = drv
         self._root = root
         self._parts = parts

     ...

class Path(PurePath):
     def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath

        # REMOVE THIS LINE: self = cls._from_parts(args, init=False) #

        if not self._flavour.is_supported:
            raise NotImplementedError("cannot instantiate %r on your system"
                                      % (cls.__name__,))
        return super().__new__(cls, *args, **kwargs) # Use super

```


I don't know what is the purpose of `_init` and if it could be replaced by an extra keyword argument in __init__.

The class method `_from_parts` would become deprecated since the argument parsing would be now handled by `__init__`.

By using __init__ and avoid the direct call to `object.__new__` we would respect class specialization and custom class could be implemented intuitively.

----------
nosy: +louis-vincent.boudre

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41109>
_______________________________________


More information about the Python-bugs-list mailing list