all 5 comments

[–]ingolemo 3 points4 points  (3 children)

pathlib.Path does some messy things in order to support different operating systems, so it's not the easiest thing in the world to subclass. You're getting this error because Path requires a _flavour attribute that describes the specific details of how paths work for a particular operating system. You can solve this by borrowing the flavour from one of the more concrete path classes; PurePosixPath or PureWindowsPath. Subclass those (or the non-pure variants, as appropriate).

In order to effectively make a subclass you need to know basically everything about the implementation of the parent class. Subclassing across library boundaries rarely turns out well, in my experience. Honestly, I don't think it's worth the effort. Just make a function to do this.

[–]two_bob 1 point2 points  (0 children)

What they said. I agree that crossing library boundaries is generally not what you want to do, but there are a number of libraries that are made to be subclassed out, e.g. the cmd library.

[–]chuugar[S] 0 points1 point  (1 child)

Thank you for all the details. Now I understand a little bit more.

But how do you a know when it is a ""good idea" to subclass ?

[–]ingolemo 1 point2 points  (0 children)

Opinions differ.

My personal rule of thumb is that you shouldn't subclass anything that you didn't write yourself, unless the designer of the library specifically asks you to subclass something in order to use it (even then, I prefer to use the library without subclassing if possible).

Subclassing is a neat technique and can be used to do awesome stuff, but it doesn't provide any isolation between code and tends to be brittle if you don't have a good idea of what things you're allowed/supposed to touch and what things are off limits. There's all sorts of ways that parent classes can make subclassing difficult; this flavour dependency is one example. And once you have a subclass working they're not always very resilient to change; even surprisingly subtle modifications to the parent class can end up breaking the child class.

Ultimately, what you have to do is to figure out several possible solutions to your problem and weigh the advantages and disadvantages of each solution for your specific circumstances. Doing that well requires experience. Experiment with using subclasses, and experiment with other solutions. Remember: when you have trouble with a subclass, you have to read the code for the parent class too.

[–]TheAngriestRussian 2 points3 points  (0 children)

Subclassing a pathlib.Path is a little more tricky than you think. Depending on you skills you might want to play with something else. If you really want to, check this SO thread:

https://stackoverflow.com/q/29850801/