or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

execution.mdindex.mditerator-dict.mdmetaclass.mdmoves.mdstring-bytes.mdtesting.mdversion-detection.md
tile.json

tessl/pypi-six

Python 2 and 3 compatibility utilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/six@1.17.x

To install, run

npx @tessl/cli install tessl/pypi-six@1.17.0

index.mddocs/

Six

Six 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.

Package Information

  • Package Name: six
  • Language: Python
  • Installation: pip install six
  • Python Support: Python 2.7 and 3.3+

Core Imports

import six

Direct attribute access:

from six import PY2, PY3, string_types, text_type, binary_type

Import specific utilities:

from six import iteritems, iterkeys, itervalues
from six import ensure_text, ensure_binary, ensure_str
from six import with_metaclass, add_metaclass

Basic Usage

import 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):
    pass

Architecture

Six provides compatibility through several key mechanisms:

  • Version Detection: Constants (PY2, PY3, PY34) for version-specific branching
  • Type Constants: Unified type checking across Python versions
  • Utility Functions: Cross-version implementations of common operations
  • Moves Module: Lazy loading system for relocated standard library modules
  • String/Bytes Handling: Utilities for text/binary data consistency
  • Metaclass Support: Decorators and utilities for cross-version metaclass usage

The library is designed as a single module with no dependencies, making it easy to integrate into any Python project requiring version compatibility.

Capabilities

Version Detection and Type Constants

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 value

Version Detection

Moves Module

The 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) -> None

Moves Module

String and Bytes Utilities

Utilities 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') -> str

String and Bytes

Iterator and Dictionary Utilities

Functions 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) -> Any

Iterator and Dictionary

Execution and Exception Utilities

Utilities 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) -> None

Execution Utilities

Metaclass and Decorator Utilities

Utilities 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) -> type

Metaclass Utilities

Testing Utilities

Utilities 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) -> None

Testing Utilities

Types

class 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)