ooppython-3.4

Subclass `pathlib.Path` fails


I would like to enhance the class pathlib.Path but the simple example above dose not work.

from pathlib import Path

class PPath(Path):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

test = PPath("dir", "test.txt")

Here is the error message I have.

Traceback (most recent call last):
  File "/Users/projetmbc/test.py", line 14, in <module>
    test = PPath("dir", "test.txt")
  File "/anaconda/lib/python3.4/pathlib.py", line 907, in __new__
    self = cls._from_parts(args, init=False)
  File "/anaconda/lib/python3.4/pathlib.py", line 589, in _from_parts
    drv, root, parts = self._parse_args(args)
  File "/anaconda/lib/python3.4/pathlib.py", line 582, in _parse_args
    return cls._flavour.parse_parts(parts)
AttributeError: type object 'PPath' has no attribute '_flavour'

What I am doing wrong ?


Solution

  • With the latest Python version, _flavour, _posix_falvour are deprecated and we can pass flavour keyword in our class.

    import os
    from pathlib import Path
    
    
    class PPath(Path):
        def __init__(self, *args) -> None:
            # Determine the flavor based on the operating system
            flavour = 'posix' if os.name == 'posix' else 'windows'
    
            # Pass the flavor to the superclass constructor
            super().__init__(*args, flavour=flavour)