I\'m trying to sublclass Path from pathlib, but I failed with following error at instantiation
from pathlib import Path
class Pl(Path):
def __init__(self
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:
The code will look like this:
import os
if os.name == 'posix':
base = PosixPath
else:
base = WindowsPath
class P1(base):
def __init__(self, *pathsegments: str):
super().__init__(*pathsegments)
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 __init__(self, *pathsegments: str):
super().__init__(*pathsegments)
Part of the problem is that the Path
class implements some conditional logic in __new__
that doesn't really lend itself to subclassing. Specifically:
def __new__(cls, *args, **kwargs):
if cls is Path:
cls = WindowsPath if os.name == 'nt' else PosixPath
This sets the type of the object you get back from Path(...)
to either PosixPath
or WindowsPath
, but only if cls is Path
, which will never be true for a subclass of Path
.
That means within the __new__
function, cls won't have the
_flavourattribute (which is set explicitly for the
*WindowsPath and *PosixPath
classes), because your Pl
class doesn't have a _flavour
attribute.
I think you would be better off explicitly subclassing one of the other classes, such as PosixPath
or WindowsPath
.
I solved it. Mokey patching is the way to go.
define functions just like this
def method1(self, other):
blah
Path.method1 = method1
The fastest, easiest, most convenient solution, zero downsides. Autosuggest in Pycharm works well.
UPDATE:
I got THE solution (works with linter and auto suggestor):
class MyPath(type(Path()), Path):
pass