or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Six

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: six

7

- **Language**: Python

8

- **Installation**: `pip install six`

9

- **Python Support**: Python 2.7 and 3.3+

10

11

## Core Imports

12

13

```python

14

import six

15

```

16

17

Direct attribute access:

18

19

```python

20

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

21

```

22

23

Import specific utilities:

24

25

```python

26

from six import iteritems, iterkeys, itervalues

27

from six import ensure_text, ensure_binary, ensure_str

28

from six import with_metaclass, add_metaclass

29

```

30

31

## Basic Usage

32

33

```python

34

import six

35

36

# Version detection

37

if six.PY2:

38

# Python 2 specific code

39

print("Running on Python 2")

40

elif six.PY3:

41

# Python 3 specific code

42

print("Running on Python 3")

43

44

# Type checking with compatibility

45

data = "hello world"

46

if isinstance(data, six.string_types):

47

print("This works on both Python 2 and 3")

48

49

# String/bytes handling

50

text = six.ensure_text("hello") # Always returns text/unicode

51

binary = six.ensure_binary("hello") # Always returns bytes/str

52

53

# Dictionary iteration

54

my_dict = {"a": 1, "b": 2, "c": 3}

55

for key, value in six.iteritems(my_dict):

56

print(f"{key}: {value}")

57

58

# Accessing relocated modules

59

from six.moves import urllib

60

response = urllib.request.urlopen('http://example.com')

61

62

# Metaclass compatibility

63

@six.add_metaclass(type)

64

class MyClass(object):

65

pass

66

```

67

68

## Architecture

69

70

Six provides compatibility through several key mechanisms:

71

72

- **Version Detection**: Constants (PY2, PY3, PY34) for version-specific branching

73

- **Type Constants**: Unified type checking across Python versions

74

- **Utility Functions**: Cross-version implementations of common operations

75

- **Moves Module**: Lazy loading system for relocated standard library modules

76

- **String/Bytes Handling**: Utilities for text/binary data consistency

77

- **Metaclass Support**: Decorators and utilities for cross-version metaclass usage

78

79

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

80

81

## Capabilities

82

83

### Version Detection and Type Constants

84

85

Core constants and type definitions for Python version detection and cross-version type checking.

86

87

```python { .api }

88

PY2: bool # True if Python 2

89

PY3: bool # True if Python 3

90

PY34: bool # True if Python 3.4+

91

92

string_types: tuple # String types for isinstance()

93

integer_types: tuple # Integer types for isinstance()

94

class_types: tuple # Class types for isinstance()

95

text_type: type # Text string type (str/unicode)

96

binary_type: type # Binary string type (bytes/str)

97

MAXSIZE: int # Maximum integer value

98

```

99

100

[Version Detection](./version-detection.md)

101

102

### Moves Module

103

104

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.

105

106

```python { .api }

107

moves: ModuleType # Main moves module

108

def add_move(item: MovedAttribute | MovedModule) -> None

109

def remove_move(name: str) -> None

110

```

111

112

[Moves Module](./moves.md)

113

114

### String and Bytes Utilities

115

116

Utilities for handling string and bytes data consistently across Python versions, including literal creation, encoding/decoding, and type coercion.

117

118

```python { .api }

119

def b(s: str) -> bytes # Create byte literal

120

def u(s: str) -> str # Create text literal

121

def ensure_binary(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> bytes

122

def ensure_text(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> str

123

def ensure_str(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> str

124

```

125

126

[String and Bytes](./string-bytes.md)

127

128

### Iterator and Dictionary Utilities

129

130

Functions for dictionary iteration and general iterator handling that work consistently across Python versions.

131

132

```python { .api }

133

def iterkeys(d: dict, **kw) -> Iterator[Any]

134

def itervalues(d: dict, **kw) -> Iterator[Any]

135

def iteritems(d: dict, **kw) -> Iterator[tuple[Any, Any]]

136

def viewkeys(d: dict) -> Any

137

def viewvalues(d: dict) -> Any

138

def viewitems(d: dict) -> Any

139

```

140

141

[Iterator and Dictionary](./iterator-dict.md)

142

143

### Execution and Exception Utilities

144

145

Utilities for code execution, exception handling, and print functionality that work across Python versions.

146

147

```python { .api }

148

def exec_(_code_: str | CodeType, _globs_: dict | None = None, _locs_: dict | None = None) -> None

149

def reraise(tp: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None = None) -> None

150

def raise_from(value: BaseException, from_value: BaseException | None) -> None

151

def print_(*args, **kwargs) -> None

152

```

153

154

[Execution Utilities](./execution.md)

155

156

### Metaclass and Decorator Utilities

157

158

Utilities for working with metaclasses and creating decorators that work across Python versions.

159

160

```python { .api }

161

def with_metaclass(meta: type, *bases: type) -> type

162

def add_metaclass(metaclass: type) -> Callable[[type], type]

163

def wraps(wrapped: Callable) -> Callable[[Callable], Callable]

164

def python_2_unicode_compatible(cls: type) -> type

165

```

166

167

[Metaclass Utilities](./metaclass.md)

168

169

### Testing Utilities

170

171

Utilities for writing tests that work across Python versions, including assertion method compatibility.

172

173

```python { .api }

174

def assertCountEqual(self, *args, **kwargs) -> None

175

def assertRaisesRegex(self, *args, **kwargs) -> ContextManager

176

def assertRegex(self, *args, **kwargs) -> None

177

def assertNotRegex(self, *args, **kwargs) -> None

178

```

179

180

[Testing Utilities](./testing.md)

181

182

## Types

183

184

```python { .api }

185

class Iterator:

186

"""Base iterator class for Python 2 compatibility."""

187

def __iter__(self) -> Iterator

188

def __next__(self) -> Any

189

190

class MovedAttribute:

191

"""Descriptor for moved attributes."""

192

def __init__(self, name: str, old_mod: str, new_mod: str, old_attr: str | None = None, new_attr: str | None = None)

193

194

class MovedModule:

195

"""Descriptor for moved modules."""

196

def __init__(self, name: str, old: str, new: str | None = None)

197

```