[New-bugs-announce] [issue30957] pathlib: Path and PurePath cannot be subclassed

Simon Bernier St-Pierre report at bugs.python.org
Tue Jul 18 02:40:11 EDT 2017


New submission from Simon Bernier St-Pierre:

Because of the special way Path and PurePath are instantiated, they can't be inherited like a normal class. Here's an example of the issue:

>>> import pathlib
>>> class MyPath(pathlib.Path):
...   pass
... 
>>> p = MyPath('/home')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/pathlib.py", line 969, in __new__
    self = cls._from_parts(args, init=False)
  File "/usr/lib/python3.5/pathlib.py", line 651, in _from_parts
    drv, root, parts = self._parse_args(args)
  File "/usr/lib/python3.5/pathlib.py", line 644, in _parse_args
    return cls._flavour.parse_parts(parts)
AttributeError: type object 'MyPath' has no attribute '_flavour'

A solution is to get the concrete type of Path via type(Path()) and inherit the class it yields, but it isn't pretty or intuitive. Perhaps a declaration that directs to the proper class could be added to the module.

PlatformPath = WindowsPath if os.name == 'nt' else PosixPath
PurePlatformPath = ...

----------
components: Library (Lib)
messages: 298577
nosy: Simon Bernier St-Pierre
priority: normal
severity: normal
status: open
title: pathlib: Path and PurePath cannot be subclassed
type: enhancement
versions: Python 3.4, Python 3.5, Python 3.6, Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30957>
_______________________________________


More information about the New-bugs-announce mailing list