It seems that this method was brought up in a bug report here. Some code was written (given here) but unfortunately it doesn't seem that it made it into the final Python 3.4 release.
Incidentally the code that was proposed was extremely similar to the code you have in your question:
# As a method of a Path object
def expanduser(self):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return self.__class__(os.path.expanduser(str(self)))
EDIT
Here is a rudimentary subclassed version PathTest
which subclasses WindowsPath
(I'm on a Windows box but you could replace it with PosixPath
). It adds a classmethod
based on the code that was submitted in the bug report.
from pathlib import WindowsPath
import os.path
class PathTest(WindowsPath):
def __new__(cls, *args, **kwargs):
return super(PathTest, cls).__new__(cls, *args, **kwargs)
@classmethod
def expanduser(cls):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return cls(os.path.expanduser('~'))
p = PathTest('C:/')
print(p) # 'C:/'
q = PathTest.expanduser()
print(q) # C:\Users\Username