Add `os.path.home`

I frequently use os.path.expanduser to just retrieve the user’s home directory: os.path.expanduser("~"). I think it would be convenient to have a shorthand for this, like os.path.home. I find the current approach to this a little bit clumsy. It seems to me that retrieving this home directory should be available as an atomic operation.

Example:

Before:

path = os.path.join(os.path.expanduser("~"), args.folder)
path = os.path.expanduser(os.path.join("~", args.folder))

After:

path = os.path.join(os.path.home, args.folder)

What do others think?

If it helps, Path.home() already exists. You could write this as:

from pathlib import Path
# ...
path = Path.home() / args.folder

Note that what os.path.expanduser("~") evaluates to can change at runtime, so if something like this were added, it would likely need to be as a function (os.path.home()) instead of as a fixed string (os.path.home).

11 Likes

I would prefer a function: os.path.home().

3 Likes

Good point. os.path.home() sounds reasonable.

Plus, home() allows it to accept an optional argument for the username. Obviously that won’t work on all platforms, but it’d be natural to be able to use os.path.home("fred") as equivalent to os.path.expanduser("~fred") where that is meaningful.

4 Likes