I’m working on a Python project initially coded with path.py 16.4
, where it was possible to create an empty Path object with Path()
. After migrating to pathlib
, this is no longer possible as Path()
now returns the current directory (.
).
My goal is to create a separate class that:
- Allows creating an empty Path object
- Returns
''
(empty string) - Has a boolean evaluation of
False
- Allows using
Path
methods - Doesn’t modify the behavior of other
Path
instances (their boolean evaluation should remain unchanged)
I’m considering three approaches and would like the community’s opinion to understand and make the right choice:
-
Composition:
from pathlib import Path class EmptyPath: def __init__(self): self._path = Path()
-
Inheritance
from pathlib import Path class EmptyPath(Path): _flavour = type(Path())._flavour def __new__(cls, *args, **kwargs): self = super().__new__(cls, '') return self
-
Metaclass
from pathlib import Path class EmptyPath(type(Path())): def __new__(cls, *args, **kwargs): return super().__new__(cls, '')
The rest of the code being this :
def __bool__(self):
"""
Override the boolean evaluation of the Path making the EmptyPath object
falsy in boolean contexts.
return: Always returns False.
"""
return False
def __str__(self):
"""
Return a string representation of the path.
For compatibility with path.py, this returns an empty string.
"""
return ''
def __repr__(self):
"""
Return a string representation for debugging.
"""
return f"EmptyPath('{self}')"
Which approach would be most appropriate to create an EmptyPath
class compatible with pathlib
? Are there specific advantages or disadvantages to each method in this context?