Skip to content

Instantly share code, notes, and snippets.

@blaylockbk
Last active August 8, 2021 00:35
Show Gist options
  • Save blaylockbk/d7504bfb6ee5426bca550b9af0bf8fc6 to your computer and use it in GitHub Desktop.
Save blaylockbk/d7504bfb6ee5426bca550b9af0bf8fc6 to your computer and use it in GitHub Desktop.
Fully Expand a pathlib.Path
# Brian Blaylock
# August 7, 2021
"""
It is often necessary to fully expand a pathlib.Path object when the
path is given a ~ or environment variables. This custom method
attachs to Path a method that fully expands these to the full path.
For example, Path('${HOME}/this/dir).expand() becomes
PosixPath('/user/name/this/dir').
"""
from pathlib import Path
def _expand(self):
"""
Fully expand and resolve the Path given environment variables.
Example
-------
>>> Path('$HOME').expand()
>>> PosixPath('/p/home/blaylock')
"""
return Path(os.path.expandvars(self)).expanduser().resolve()
Path.expand = _expand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment