Python Version Detection Code Snippets
Ready-to-use Python code snippets to detect which Python version is running. Check version compatibility and handle version-specific features.
Python Version Detection Code Snippets
These code snippets help you detect which Python version is currently running and handle version-specific functionality in your applications.
Basic Version Detection #
Simple Version Check #
import sys
# Get current Python version as string
python_version = sys.version
print(f"Full version info: {python_version}")
# Get version tuple (major, minor, micro, releaselevel, serial)
version_info = sys.version_info
print(f"Version info: {version_info}")
# Extract major and minor version
major_minor = f"{version_info.major}.{version_info.minor}"
print(f"Python {major_minor}")
Version Comparison Utility #
import sys
def check_python_version(min_version_tuple):
"""
Check if current Python version meets minimum requirements.
Args:
min_version_tuple: Tuple like (3, 8) for minimum version
Returns:
bool: True if version requirement is met
"""
return sys.version_info >= min_version_tuple
# Usage examples
if check_python_version((3, 8)):
print("✅ Python 3.8+ requirement met")
else:
print("❌ Python 3.8+ required")
# Check for specific features
if check_python_version((3, 10)):
print("✅ Can use match/case statements")
if check_python_version((3, 11)):
print("✅ Enhanced error messages available")
Advanced Version Detection #
Comprehensive Version Reporter #
🐍 Try it yourself
Version-Specific Feature Detection #
import sys
class PythonFeatures:
"""Detect which Python version features are available."""
@staticmethod
def has_walrus_operator():
"""Check if := operator is available (Python 3.8+)"""
return sys.version_info >= (3, 8)
@staticmethod
def has_positional_only_params():
"""Check if positional-only parameters are available (Python 3.8+)"""
return sys.version_info >= (3, 8)
@staticmethod
def has_match_case():
"""Check if match/case statements are available (Python 3.10+)"""
return sys.version_info >= (3, 10)
@staticmethod
def has_enhanced_error_messages():
"""Check if enhanced error messages are available (Python 3.11+)"""
return sys.version_info >= (3, 11)
@staticmethod
def has_exception_groups():
"""Check if exception groups are available (Python 3.11+)"""
return sys.version_info >= (3, 11)
# Test feature availability
features = PythonFeatures()
print(f"Walrus operator (:=): {features.has_walrus_operator()}")
print(f"Match/case statements: {features.has_match_case()}")
print(f"Enhanced errors: {features.has_enhanced_error_messages()}")
Version-Conditional Code Execution #
Conditional Import Based on Version #
import sys
# Version-specific imports
if sys.version_info >= (3, 11):
# Use newer asyncio features
from asyncio import TaskGroup
print("Using Python 3.11+ TaskGroup")
else:
# Fallback for older versions
print("Using compatibility layer for older Python")
# Conditional feature usage
def example_function():
if sys.version_info >= (3, 10):
# Use match/case (Python 3.10+)
value = "example"
match value:
case "example":
return "Using match/case"
case _:
return "Default case"
else:
# Use traditional if/elif
value = "example"
if value == "example":
return "Using if/elif"
else:
return "Default case"
result = example_function()
print(result)
Version Compatibility Decorator #
import sys
from functools import wraps
def requires_python_version(min_version):
"""
Decorator to ensure function runs on specified Python version or higher.
Args:
min_version: Tuple like (3, 8) for minimum required version
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if sys.version_info < min_version:
version_str = '.'.join(map(str, min_version))
current_str = f"{sys.version_info.major}.{sys.version_info.minor}"
raise RuntimeError(
f"Function '{func.__name__}' requires Python {version_str}+, "
f"but you're running Python {current_str}"
)
return func(*args, **kwargs)
return wrapper
return decorator
# Usage example
@requires_python_version((3, 8))
def use_walrus_operator():
"""Function that uses walrus operator (Python 3.8+)"""
if (n := len("test")) > 3:
return f"String length: {n}"
return "Short string"
# This will work on Python 3.8+ or raise an error
try:
result = use_walrus_operator()
print(result)
except RuntimeError as e:
print(f"Error: {e}")
Environment and Package Version Detection #
Python Environment Inspector #
🐍 Try it yourself
Package Version Compatibility Checker #
import sys
import importlib
import pkg_resources
def check_package_python_compatibility(package_name):
"""
Check if a package is compatible with current Python version.
Args:
package_name: Name of the package to check
Returns:
dict: Compatibility information
"""
try:
# Try to import the package
package = importlib.import_module(package_name)
# Get package version if available
try:
dist = pkg_resources.get_distribution(package_name)
version = dist.version
except pkg_resources.DistributionNotFound:
version = "Unknown"
# Get Python version requirements if available
python_requires = None
try:
metadata = dist.get_metadata('METADATA')
for line in metadata.split('\n'):
if line.startswith('Requires-Python:'):
python_requires = line.split(':', 1)[1].strip()
break
except:
pass
return {
'package': package_name,
'version': version,
'python_requires': python_requires,
'compatible': True,
'current_python': f"{sys.version_info.major}.{sys.version_info.minor}"
}
except ImportError:
return {
'package': package_name,
'version': None,
'python_requires': None,
'compatible': False,
'current_python': f"{sys.version_info.major}.{sys.version_info.minor}",
'error': 'Package not found or not compatible'
}
# Example usage
packages_to_check = ['numpy', 'pandas', 'requests']
for package in packages_to_check:
info = check_package_python_compatibility(package)
status = "✅" if info['compatible'] else "❌"
print(f"{status} {package}: {info}")
Summary #
These code snippets provide comprehensive tools for detecting which Python version is running and handling version-specific functionality:
- Basic detection: Simple version checks and comparisons
- Advanced reporting: Comprehensive environment information
- Feature detection: Check availability of version-specific features
- Conditional execution: Run different code based on Python version
- Environment inspection: Analyze virtual environments and package compatibility
Use these snippets to ensure your Python applications work correctly across different Python versions and environments.