Path
is somewhat of an abstract class that is actually instantiated as on of two possible subclasses depending on the OS:
PosixPath
or WindowsPath
https://docs.python.org/3/library/pathlib.html
This base class looks for an internal (private) class variable to determine what type of object it actually is, and this variable is called _flavour
You have two choices:
- Derive your class from one of the concrete subclasses.
This is the best choice as it will save you dealing with undocumented library internals and guarantee your code will not break on different versions of the library.
You will need to define your class differently based on the OS if you want your code to be cross-platform.
EDIT: Following dank8's comment, the original sample code had an issue: Path
does not take __init__
parameters, but __new__
parameters instead.
Also, there is a better way to determine concrete subclass at runtime.
The code will look like this:
from pathlib import Path
class P1(type(Path())):
def __new__(cls, *pathsegments):
return super().__new__(cls, *pathsegments)
- Alternatively fill in the class variable yourself.
This is not recommended as you will be using undocumented elements that could break at any time with any change to the library, but it will allow you to inherit from Path
directly.
Note, there may be other issues if you decide to use this method!
import os
from pathlib import _PosixFlavour
from pathlib import _WindowsFlavour
class P1(Path):
_flavour = _PosixFlavour() if os.name == 'posix' else _WindowsFlavour()
def __new__(cls, *pathsegments):
return super().__new__(cls, *pathsegments)