Python 2 and 3 compatibility utilities
npx @tessl/cli install tessl/pypi-six@1.17.0Six is a Python 2 and 3 compatibility library that provides utility functions for smoothing over the differences between Python versions with the goal of writing Python code that is compatible on both Python versions. It is a single-file library that can be easily integrated into projects, offering comprehensive compatibility utilities including string/text handling, iteration utilities, metaclass management, and import handling.
pip install siximport sixDirect attribute access:
from six import PY2, PY3, string_types, text_type, binary_typeImport specific utilities:
from six import iteritems, iterkeys, itervalues
from six import ensure_text, ensure_binary, ensure_str
from six import with_metaclass, add_metaclassimport six
# Version detection
if six.PY2:
# Python 2 specific code
print("Running on Python 2")
elif six.PY3:
# Python 3 specific code
print("Running on Python 3")
# Type checking with compatibility
data = "hello world"
if isinstance(data, six.string_types):
print("This works on both Python 2 and 3")
# String/bytes handling
text = six.ensure_text("hello") # Always returns text/unicode
binary = six.ensure_binary("hello") # Always returns bytes/str
# Dictionary iteration
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in six.iteritems(my_dict):
print(f"{key}: {value}")
# Accessing relocated modules
from six.moves import urllib
response = urllib.request.urlopen('http://example.com')
# Metaclass compatibility
@six.add_metaclass(type)
class MyClass(object):
passSix provides compatibility through several key mechanisms:
The library is designed as a single module with no dependencies, making it easy to integrate into any Python project requiring version compatibility.
Core constants and type definitions for Python version detection and cross-version type checking.
PY2: bool # True if Python 2
PY3: bool # True if Python 3
PY34: bool # True if Python 3.4+
string_types: tuple # String types for isinstance()
integer_types: tuple # Integer types for isinstance()
class_types: tuple # Class types for isinstance()
text_type: type # Text string type (str/unicode)
binary_type: type # Binary string type (bytes/str)
MAXSIZE: int # Maximum integer valueThe six.moves module provides unified access to standard library modules and functions that were moved or renamed between Python 2 and 3, supporting 70+ relocated imports.
moves: ModuleType # Main moves module
def add_move(item: MovedAttribute | MovedModule) -> None
def remove_move(name: str) -> NoneUtilities for handling string and bytes data consistently across Python versions, including literal creation, encoding/decoding, and type coercion.
def b(s: str) -> bytes # Create byte literal
def u(s: str) -> str # Create text literal
def ensure_binary(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> bytes
def ensure_text(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> str
def ensure_str(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> strFunctions for dictionary iteration and general iterator handling that work consistently across Python versions.
def iterkeys(d: dict, **kw) -> Iterator[Any]
def itervalues(d: dict, **kw) -> Iterator[Any]
def iteritems(d: dict, **kw) -> Iterator[tuple[Any, Any]]
def viewkeys(d: dict) -> Any
def viewvalues(d: dict) -> Any
def viewitems(d: dict) -> AnyUtilities for code execution, exception handling, and print functionality that work across Python versions.
def exec_(_code_: str | CodeType, _globs_: dict | None = None, _locs_: dict | None = None) -> None
def reraise(tp: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None = None) -> None
def raise_from(value: BaseException, from_value: BaseException | None) -> None
def print_(*args, **kwargs) -> NoneUtilities for working with metaclasses and creating decorators that work across Python versions.
def with_metaclass(meta: type, *bases: type) -> type
def add_metaclass(metaclass: type) -> Callable[[type], type]
def wraps(wrapped: Callable) -> Callable[[Callable], Callable]
def python_2_unicode_compatible(cls: type) -> typeUtilities for writing tests that work across Python versions, including assertion method compatibility.
def assertCountEqual(self, *args, **kwargs) -> None
def assertRaisesRegex(self, *args, **kwargs) -> ContextManager
def assertRegex(self, *args, **kwargs) -> None
def assertNotRegex(self, *args, **kwargs) -> Noneclass Iterator:
"""Base iterator class for Python 2 compatibility."""
def __iter__(self) -> Iterator
def __next__(self) -> Any
class MovedAttribute:
"""Descriptor for moved attributes."""
def __init__(self, name: str, old_mod: str, new_mod: str, old_attr: str | None = None, new_attr: str | None = None)
class MovedModule:
"""Descriptor for moved modules."""
def __init__(self, name: str, old: str, new: str | None = None)