or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-mypy-extensions

Type system extensions for programs checked with the mypy type checker.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/mypy-extensions@1.1.x

To install, run

npx @tessl/cli install tessl/pypi-mypy-extensions@1.1.0

0

# mypy-extensions

1

2

Type system extensions for programs checked with the mypy type checker. This package provides experimental extensions to Python's standard typing module that are specifically supported by the mypy type checker and mypyc compiler.

3

4

## Package Information

5

6

- **Package Name**: mypy-extensions

7

- **Language**: Python

8

- **Installation**: `pip install mypy-extensions`

9

- **Python Version Support**: 3.8+

10

11

## Core Imports

12

13

```python

14

import mypy_extensions

15

```

16

17

Import specific components:

18

19

```python

20

from mypy_extensions import TypedDict, i64, i32, i16, u8

21

from mypy_extensions import Arg, DefaultArg, NamedArg, DefaultNamedArg, VarArg, KwArg

22

from mypy_extensions import trait, mypyc_attr, FlexibleAlias

23

```

24

25

For typing support in function signatures:

26

27

```python

28

from typing import Any # Used in mypy_extensions function signatures

29

```

30

31

## Basic Usage

32

33

```python

34

from mypy_extensions import TypedDict, i64, i32, trait

35

36

# TypedDict usage (deprecated - use typing.TypedDict instead)

37

import warnings

38

with warnings.catch_warnings():

39

warnings.simplefilter("ignore", DeprecationWarning)

40

41

Point2D = TypedDict('Point2D', {'x': int, 'y': int})

42

point = Point2D(x=1, y=2)

43

print(point) # {'x': 1, 'y': 2}

44

45

# Native integer types for mypyc

46

big_number = i64(2**63 - 1) # Behaves like int() at runtime

47

small_number = i32(42)

48

49

# Trait decorator

50

@trait

51

class Drawable:

52

def draw(self) -> None: ...

53

```

54

55

## Capabilities

56

57

### TypedDict (Deprecated)

58

59

Creates dictionary types with specific key-value type annotations for static type checking. **Note**: This is deprecated - use `typing.TypedDict` or `typing_extensions.TypedDict` instead.

60

61

```python { .api }

62

def TypedDict(typename, fields=None, *, total=True, **kwargs):

63

"""

64

Create a typed dictionary class.

65

66

Args:

67

typename (str): Name of the TypedDict class

68

fields (dict, optional): Dictionary mapping field names to types

69

total (bool): Whether all fields are required (default: True)

70

**kwargs: Alternative way to specify fields as keyword arguments

71

72

Returns:

73

type: A new TypedDict class that behaves like dict at runtime

74

75

Raises:

76

TypeError: If both fields dict and kwargs are provided

77

DeprecationWarning: Always emitted to encourage migration to typing.TypedDict

78

"""

79

```

80

81

Usage patterns:

82

83

```python

84

# Functional syntax with dict

85

Point2D = TypedDict('Point2D', {'x': int, 'y': int})

86

87

# Functional syntax with kwargs

88

Point2D = TypedDict('Point2D', x=int, y=int)

89

90

# Class syntax (Python 3.6+)

91

class Point2D(TypedDict):

92

x: int

93

y: int

94

95

# Partial/optional fields

96

Options = TypedDict('Options', {'debug': bool, 'verbose': bool}, total=False)

97

```

98

99

### Callable Argument Constructors

100

101

Type constructors for creating detailed Callable type annotations. These are runtime noops that return their type argument unchanged.

102

103

```python { .api }

104

def Arg(type=Any, name=None):

105

"""

106

A normal positional argument.

107

108

Args:

109

type: The argument's type (default: Any)

110

name: Optional argument name for documentation

111

112

Returns:

113

The type argument unchanged

114

"""

115

116

def DefaultArg(type=Any, name=None):

117

"""

118

A positional argument with a default value.

119

120

Args:

121

type: The argument's type (default: Any)

122

name: Optional argument name for documentation

123

124

Returns:

125

The type argument unchanged

126

"""

127

128

def NamedArg(type=Any, name=None):

129

"""

130

A keyword-only argument.

131

132

Args:

133

type: The argument's type (default: Any)

134

name: Optional argument name for documentation

135

136

Returns:

137

The type argument unchanged

138

"""

139

140

def DefaultNamedArg(type=Any, name=None):

141

"""

142

A keyword-only argument with a default value.

143

144

Args:

145

type: The argument's type (default: Any)

146

name: Optional argument name for documentation

147

148

Returns:

149

The type argument unchanged

150

"""

151

152

def VarArg(type=Any):

153

"""

154

A *args-style variadic positional argument.

155

156

Args:

157

type: The type of the variadic arguments (default: Any)

158

159

Returns:

160

The type argument unchanged

161

"""

162

163

def KwArg(type=Any):

164

"""

165

A **kwargs-style variadic keyword argument.

166

167

Args:

168

type: The type of the variadic keyword arguments (default: Any)

169

170

Returns:

171

The type argument unchanged

172

"""

173

```

174

175

### Native Integer Types (mypyc)

176

177

Fixed-width integer types that provide mypyc-specific optimizations while maintaining `int` compatibility at runtime.

178

179

```python { .api }

180

class i64:

181

"""

182

64-bit signed integer type for mypyc compilation.

183

184

Behaves like int() at runtime:

185

- Constructor converts numbers/strings to int

186

- isinstance(x, i64) equivalent to isinstance(x, int)

187

"""

188

def __new__(cls, x=0, base=None):

189

"""

190

Create a 64-bit integer.

191

192

Args:

193

x: Number or string to convert (default: 0)

194

base: Number base for string conversion (optional)

195

196

Returns:

197

int: The converted integer value

198

"""

199

200

class i32:

201

"""

202

32-bit signed integer type for mypyc compilation.

203

204

Behaves like int() at runtime:

205

- Constructor converts numbers/strings to int

206

- isinstance(x, i32) equivalent to isinstance(x, int)

207

"""

208

def __new__(cls, x=0, base=None):

209

"""

210

Create a 32-bit integer.

211

212

Args:

213

x: Number or string to convert (default: 0)

214

base: Number base for string conversion (optional)

215

216

Returns:

217

int: The converted integer value

218

"""

219

220

class i16:

221

"""

222

16-bit signed integer type for mypyc compilation.

223

224

Behaves like int() at runtime:

225

- Constructor converts numbers/strings to int

226

- isinstance(x, i16) equivalent to isinstance(x, int)

227

"""

228

def __new__(cls, x=0, base=None):

229

"""

230

Create a 16-bit integer.

231

232

Args:

233

x: Number or string to convert (default: 0)

234

base: Number base for string conversion (optional)

235

236

Returns:

237

int: The converted integer value

238

"""

239

240

class u8:

241

"""

242

8-bit unsigned integer type for mypyc compilation.

243

244

Behaves like int() at runtime:

245

- Constructor converts numbers/strings to int

246

- isinstance(x, u8) equivalent to isinstance(x, int)

247

"""

248

def __new__(cls, x=0, base=None):

249

"""

250

Create an 8-bit unsigned integer.

251

252

Args:

253

x: Number or string to convert (default: 0)

254

base: Number base for string conversion (optional)

255

256

Returns:

257

int: The converted integer value

258

"""

259

```

260

261

Usage example:

262

263

```python

264

# These behave like int() at runtime but provide type hints for mypyc

265

count = i32(42)

266

big_id = i64(2**50)

267

small_flag = u8(255)

268

hex_value = i16("ff", 16) # Convert hex string

269

270

# Type checking with isinstance

271

assert isinstance(count, i32) # True (equivalent to isinstance(count, int))

272

assert isinstance(count, int) # Also True

273

```

274

275

### Decorators and Utilities

276

277

#### Trait Decorator

278

279

```python { .api }

280

def trait(cls):

281

"""

282

Mark a class as a trait (protocol-like interface).

283

284

Args:

285

cls: The class to mark as a trait

286

287

Returns:

288

The class unchanged (identity function at runtime)

289

"""

290

```

291

292

Usage:

293

294

```python

295

@trait

296

class Drawable:

297

def draw(self) -> None: ...

298

299

@trait

300

class Serializable:

301

def serialize(self) -> bytes: ...

302

```

303

304

#### mypyc Attribute Decorator

305

306

```python { .api }

307

def mypyc_attr(*attrs, **kwattrs):

308

"""

309

Decorator for specifying mypyc-specific attributes on classes/functions.

310

311

Args:

312

*attrs: Positional mypyc attribute specifications

313

**kwattrs: Keyword mypyc attribute specifications

314

315

Returns:

316

Identity decorator function (noop at runtime)

317

"""

318

```

319

320

Usage:

321

322

```python

323

@mypyc_attr(allow_interpreted_subclasses=True)

324

class FastClass:

325

pass

326

```

327

328

#### FlexibleAlias

329

330

Advanced type alias construct supporting flexible parameterization.

331

332

```python { .api }

333

FlexibleAlias: _FlexibleAliasCls

334

"""

335

Advanced type alias that supports flexible parameterization.

336

Used with subscript syntax for complex type aliasing scenarios.

337

"""

338

```

339

340

Usage:

341

342

```python

343

# Used in complex type aliasing scenarios

344

MyAlias = FlexibleAlias[int, str, bool]

345

```

346

347

### Deprecated Components

348

349

#### NoReturn

350

351

```python { .api }

352

# Accessible via module attribute access - triggers DeprecationWarning

353

NoReturn: type

354

"""

355

Type indicating a function never returns (deprecated).

356

357

Use typing.NoReturn or typing_extensions.NoReturn instead.

358

359

Raises:

360

DeprecationWarning: Always emitted when accessed

361

"""

362

```

363

364

Usage (deprecated):

365

366

```python

367

import warnings

368

with warnings.catch_warnings():

369

warnings.simplefilter("ignore", DeprecationWarning)

370

371

from mypy_extensions import NoReturn

372

373

def never_returns() -> NoReturn:

374

raise RuntimeError("This never returns")

375

```

376

377

## Error Handling

378

379

### TypedDict Errors

380

381

```python

382

# TypeError when using isinstance/issubclass

383

Point2D = TypedDict('Point2D', {'x': int, 'y': int})

384

isinstance({}, Point2D) # Raises TypeError

385

issubclass(dict, Point2D) # Raises TypeError

386

387

# TypeError for invalid field types

388

TypedDict('Bad', {'field': ()}) # Raises TypeError

389

390

# TypeError for mixing dict and kwargs

391

TypedDict('Bad', {'x': int}, y=int) # Raises TypeError

392

```

393

394

### Deprecation Warnings

395

396

```python

397

# TypedDict usage emits DeprecationWarning

398

import warnings

399

with warnings.catch_warnings():

400

warnings.simplefilter("ignore", DeprecationWarning)

401

Point2D = TypedDict('Point2D', {'x': int, 'y': int})

402

403

# NoReturn access emits DeprecationWarning

404

from mypy_extensions import NoReturn # Warns to use typing.NoReturn

405

```

406

407

## Migration Notes

408

409

- **TypedDict**: Migrate to `typing.TypedDict` (Python 3.8+) or `typing_extensions.TypedDict`

410

- **NoReturn**: Migrate to `typing.NoReturn` (Python 3.6.2+) or `typing_extensions.NoReturn`

411

- **Callable arguments**: Continue using these for detailed Callable annotations with mypy

412

- **Native integer types**: Continue using for mypyc optimization

413

- **trait/mypyc_attr**: Continue using for mypy/mypyc integration