To determine which paths in sys.path contain standard library packages/modules and which contain user-installed libraries, Python provides a built-in mechanism starting from Python 3.12 via the sys.stdlib_paths() function.
✅ Using sys.stdlib_paths() (Python 3.12+)
This function returns a list of paths that are part of the standard Python library. These are the directories where Python's built-in modules are stored.
Example Usage:
import sys
# Get the standard library paths
stdlib_paths = sys.stdlib_paths()
# Check each path in sys.path
for path in sys.path:
if path in stdlib_paths:
print(f"{path} ← Standard Library")
else:
print(f"{path} ← User/Third-Party")
Output (example):
/usr/lib/python3.12 ← Standard Library
/usr/lib/python3.12/site-packages ← User/Third-Party
. ← User/Third-Party
🧩 For Older Python Versions (Before 3.12)
If you're using a version of Python older than 3.12, sys.stdlib_paths() is not available. In that case, you can use the sysconfig module to manually determine the standard library paths.
Example:
import sys
import sysconfig
# Get standard library paths using sysconfig
stdlib_paths = [
sysconfig.get_path('stdlib'),
sysconfig.get_path('platstdlib'),
]
# Check each path in sys.path
for path in sys.path:
if path in stdlib_paths:
print(f"{path} ← Standard Library")
else:
print(f"{path} ← User/Third-Party")
Notes:
sysconfig.get_path('stdlib') returns the standard library path.
sysconfig.get_path('platstdlib') returns the platform-specific standard library path (e.g., for OS-specific modules).
- This approach may not capture all standard paths in some environments, but it's a good starting point.
📌 Understanding the Difference
- Standard Library Paths: These are the directories where Python's core modules (like
os, sys, datetime, etc.) are stored. They are part of the Python distribution.
- User/Third-Party Paths: These are typically directories like
site-packages, which store packages installed via pip, conda, or other tools.
🔍 Additional Tips
- Virtual Environments: In a virtual environment,
sys.path includes the environment's site-packages, which are user-installed. The standard library paths in a virtual environment still point to the original Python installation.
- User-Specific Packages: These are often found in
~/.local/lib/pythonX.Y/site-packages, which is not part of the standard library.
🧠 Summary
| Feature | Description |
|---|
| ✅ Python 3.12+ | Use sys.stdlib_paths() to identify standard library paths. |
| ❌ Python < 3.12 | Use sysconfig.get_path('stdlib') and sysconfig.get_path('platstdlib'). |
| 🧩 User/Third-Party | Paths not in sys.stdlib_paths() (or the equivalent) are likely user or third-party. |
This method gives a clear distinction between standard and user-installed packages in your sys.path.