Last active
August 8, 2021 00:35
-
-
Save blaylockbk/d7504bfb6ee5426bca550b9af0bf8fc6 to your computer and use it in GitHub Desktop.
Fully Expand a pathlib.Path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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