Excellent question. This is a common task, and Python's standard library provides a powerful and cross-platform way to achieve this by combining a few functions.
Unlike the Bash realpath command, which benefits from shell expansion happening before the command runs, in Python you need to perform these steps explicitly. The modern and recommended way to do this is with the pathlib module (available since Python 3.4).
🏆 The Best Way (Python 3.4+): Using pathlib and os.path.expandvars
The most robust solution involves a three-step process, which we can wrap in a simple function:
- Expand Environment Variables: Replace
$VAR or %VAR% with their values using os.path.expandvars().
- Expand User Tilde: Replace
~ with the user's home directory path using Path.expanduser().
- Resolve the Path: Get the canonical, absolute path, resolving any symbolic links and relative segments (
. or ..) using Path.resolve().
Here is a complete function and example:
import os
from pathlib import Path
def get_absolute_path(path: str) -> Path:
"""
Gets the absolute path, expanding environment variables,
the user tilde, and resolving symbolic links.
This is the Python equivalent of `realpath` in Bash after
shell expansion.
"""
# Step 1 & 2: Expand environment variables and the user tilde.
# The Path object is created after expanding vars to handle paths like "$HOME/something".
p = Path(os.path.expandvars(path)).expanduser()
# Step 3: Resolve the path to its absolute, canonical form.
# The strict=True argument will raise a FileNotFoundError if the path doesn't exist.
# Set to False to allow resolving a non-existent path as far as possible.
return p.resolve(strict=False)
# --- EXAMPLES ---
# 1. Path with an environment variable ($HOME on Linux/macOS, %USERPROFILE% on Windows)
# Let's assume HOME is /home/user
path_with_var = "$HOME/projects/my_project"
resolved_path = get_absolute_path(path_with_var)
print(f"'{path_with_var}' -> '{resolved_path}'")
# Output: '$HOME/projects/my_project' -> '/home/user/projects/my_project'
# 2. Path with a tilde
path_with_tilde = "~/documents/report.txt"
resolved_path = get_absolute_path(path_with_tilde)
print(f"'{path_with_tilde}' -> '{resolved_path}'")
# Output: '~/documents/report.txt' -> '/home/user/documents/report.txt'
# 3. Path with relative components
# Let's assume the current working directory is /home/user/projects
path_with_dots = "../src/../main.py"
resolved_path = get_absolute_path(path_with_dots)
print(f"'{path_with_dots}' -> '{resolved_path}'")
# Output: '../src/../main.py' -> '/home/user/main.py'
# 4. A path that is a symbolic link
# If /home/user/latest -> /home/user/v1.2.3
# os.symlink('/home/user/v1.2.3', '/home/user/latest') # How you'd create it
path_with_symlink = "~/latest"
resolved_path = get_absolute_path(path_with_symlink)
print(f"'{path_with_symlink}' -> '{resolved_path}'")
# Output: '~/latest' -> '/home/user/v1.2.3'
Why This Combination?
The pathlib and os.path modules break down path manipulation into distinct, single-purpose functions. Here’s a breakdown of what each part does:
| Function / Method | What It Does | Example |
|---|
os.path.expandvars(path) | Expands environment variables like $VAR or %VAR%. It does not handle the ~. | "$HOME/file" → "/home/user/file" |
Path(path).expanduser() | Expands a leading ~ or ~user to the corresponding home directory. | "~/file" → Path('/home/user/file') |
Path(path).resolve() | Makes the path absolute and resolves all symbolic links. This is the core realpath equivalent. | Path('../link') → Path('/absolute/path/to/target') |
Path(path).absolute() | Makes a path absolute but does not resolve symbolic links. | Path('../link') → Path('/absolute/path/to/link') |
By combining them in the correct order, you build a robust tool that covers all the features you're asking for.
The "Classic" Way: Using os.path Only
If you are working on an older codebase (pre-Python 3.4) or prefer to stick to the os.path module, you can achieve the same result. The logic is identical, just with different function calls.
import os
def get_absolute_path_os(path: str) -> str:
"""
The os.path equivalent for getting a fully resolved, absolute path.
"""
# Step 1: Expand variables
path = os.path.expandvars(path)
# Step 2: Expand user tilde
path = os.path.expanduser(path)
# Step 3: Resolve to a canonical, absolute path
path = os.path.realpath(path)
return path
# Example using the os.path version
path_with_var = "$HOME/projects/my_project"
resolved_path = get_absolute_path_os(path_with_var)
print(f"'{path_with_var}' -> '{resolved_path}'")
# Output: '$HOME/projects/my_project' -> '/home/user/projects/my_project'
Summary: pathlib vs. os.path
| Feature | pathlib (Modern) | os.path (Classic) |
|---|
| Object Type | Returns a Path object with useful methods. | Returns a simple string. |
| Readability | Generally more readable and intuitive (e.g., p.resolve()). | Functional style (e.g., os.path.realpath(p)). |
| Core Functions | Path.expanduser(), Path.resolve() | os.path.expanduser(), os.path.realpath() |
| Var Expansion | Requires os.path.expandvars() | os.path.expandvars() |
| Recommendation | Preferred for new Python 3.4+ code. | Fine for older code or when you must work with strings. |
Final Recommendation: Use the pathlib-based function. It is the modern, idiomatic, and more powerful way to handle filesystem paths in Python.