You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
pathlib: Path and PurePath cannot be subclassed #75140
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
>>> classMyPath(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.
Activity
sbstp commentedon Jul 18, 2017
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:
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.
stevendaprano commentedon Jul 18, 2017
Python 3.4, 3.5 and 3.6 are in feature-freeze, so this enhancement can only apply to 3.7.
You say that pathlib.Path "can't be subclassed", but then immediately show an example of subclassing it:
Which works fine. If you run:
it returns True. Unfortunately, it looks like your subclass broke one of the class invariants, but you don't find out until you try to instantiate it:
_flavour is a private attribute, and is not documented, so I don't think subclassing is supported. If that is the case:
probably require a metaclass);
If subclassing is supported, then I think there ought to be a better way than this:
py> class MyPath(pathlib.Path):
... _flavour = pathlib.Path('.')._flavour
...
py> MyPath('.')
MyPath('.')
serhiy-storchaka commentedon Jul 18, 2017
This is a duplicate of bpo-24132.