Search code examples
pythonpython-3.4

Getting Home Directory with pathlib


Looking through the new pathlib module in Python 3.4, I notice that there isn't any simple way to get the user's home directory. The only way I can come up with for getting a user's home directory is to use the older os.path lib like so:

import pathlib
from os import path
p = pathlib.Path(path.expanduser("~"))

This seems clunky. Is there a better way?


Solution

  • 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