or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-pytype

Python type inferencer that analyzes code without requiring explicit type annotations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pytype@2024.10.x

To install, run

npx @tessl/cli install tessl/pypi-pytype@2024.10.0

0

# PyType

1

2

A static type checker and inferencer for Python that analyzes code without requiring explicit type annotations. PyType performs type inference on plain Python code to detect common programming errors like misspelled attributes and incorrect function calls, while also enforcing user-provided type annotations when present.

3

4

## Package Information

5

6

- **Package Name**: pytype

7

- **Language**: Python

8

- **Installation**: `pip install pytype`

9

- **Requirements**: Python 3.8-3.12

10

- **Platform Support**: Linux (primary), macOS 10.7+, Windows (via WSL)

11

12

## Core Imports

13

14

```python

15

import pytype

16

```

17

18

For direct API usage:

19

20

```python

21

from pytype import io

22

from pytype import config

23

from pytype import analyze

24

```

25

26

For working with PyTD (Python Type Declaration) system:

27

28

```python

29

from pytype.pytd import pytd

30

from pytype.pytd import pytd_utils

31

from pytype.pyi import parser

32

```

33

34

## Basic Usage

35

36

### Type Checking a Source String

37

38

```python

39

from pytype import io

40

41

# Check types in Python source code

42

source_code = '''

43

def add_numbers(x, y):

44

return x + y

45

46

result = add_numbers("hello", 42) # This will cause a type error

47

'''

48

49

try:

50

# Perform type checking

51

result = io.check_py(source_code)

52

print("Type checking completed successfully")

53

except Exception as e:

54

print(f"Type checking failed: {e}")

55

```

56

57

### Generating Type Stubs

58

59

```python

60

from pytype import io

61

62

# Generate .pyi type stub from source code

63

source_code = '''

64

class Calculator:

65

def add(self, x, y):

66

return x + y

67

68

def multiply(self, x, y):

69

return x * y

70

'''

71

72

# Generate PyTD AST

73

pyi_ast = io.generate_pyi_ast(source_code)

74

75

# Generate .pyi string

76

pyi_string = io.generate_pyi(source_code)

77

print(pyi_string)

78

```

79

80

### Processing Files with Configuration

81

82

```python

83

from pytype import config

84

from pytype import io

85

86

# Create configuration options

87

options = config.Options.create()

88

options.python_version = (3, 11)

89

options.output = "/path/to/output.pyi"

90

91

# Process a single file

92

result = io.process_one_file(options)

93

```

94

95

## Architecture

96

97

PyType's architecture consists of several key components:

98

99

- **Analysis Engine**: Core type inference and checking logic using abstract interpretation

100

- **PyTD System**: Python Type Declaration format for representing type information

101

- **PYI Parser**: Parser for Python type stub files (.pyi)

102

- **Configuration System**: Comprehensive options and settings management

103

- **CLI Tools**: Command-line interfaces for various analysis tasks

104

- **Import System**: Module resolution and loading infrastructure

105

106

This design enables PyType to analyze large Python codebases incrementally, generate precise type information, and integrate with existing Python development workflows through multiple interfaces.

107

108

## Capabilities

109

110

### Core Analysis Functions

111

112

High-level API for type checking and inference operations. These functions provide the primary programmatic interface to PyType's analysis capabilities.

113

114

```python { .api }

115

def check_py(src, options=None, loader=None): ...

116

def generate_pyi_ast(src, options=None, loader=None): ...

117

def generate_pyi(src, options=None, loader=None): ...

118

def process_one_file(options): ...

119

```

120

121

[Core Analysis](./core-analysis.md)

122

123

### Configuration Management

124

125

Comprehensive configuration system for controlling PyType's behavior, including Python version targeting, output formats, error handling, and analysis depth settings.

126

127

```python { .api }

128

class Options:

129

def __init__(argv_or_options, command_line=False): ...

130

@classmethod

131

def create(): ...

132

133

def make_parser(): ...

134

```

135

136

[Configuration](./configuration.md)

137

138

### PyTD Type System

139

140

Python Type Declaration system for representing, manipulating, and optimizing type information. Provides the foundation for PyType's type representation and stub file generation.

141

142

```python { .api }

143

class TypeDeclUnit: ...

144

class Class: ...

145

class Function: ...

146

def Print(ast, multiline_args=False): ...

147

def Optimize(ast, builtins, **kwargs): ...

148

```

149

150

[PyTD System](./pytd-system.md)

151

152

### PYI Parsing

153

154

Parser for Python type stub files (.pyi) that converts textual type declarations into PyTD AST representations for analysis and manipulation.

155

156

```python { .api }

157

def parse_string(src, filename=None, options=None): ...

158

def parse_pyi(src, filename, options): ...

159

def canonical_pyi(pyi, multiline_args=False, options=None): ...

160

```

161

162

[PYI Parsing](./pyi-parsing.md)

163

164

### Command-Line Tools

165

166

Complete set of command-line tools for different PyType workflows, from single-file analysis to project-wide type checking and stub generation.

167

168

```bash

169

pytype [files...] # Analyze Python projects

170

pytype-single file.py # Analyze single files

171

pytd [options] file.pytd # Process PyTD files

172

merge-pyi file.py file.pyi # Merge type stubs into source

173

annotate-ast file.py # Add type annotations to AST

174

pyxref [files...] # Generate cross-references

175

```

176

177

[CLI Tools](./cli-tools.md)

178

179

### Module Loading

180

181

Infrastructure for loading and resolving Python modules, PyTD files, and type information with support for custom import mappings and pickled type data.

182

183

```python { .api }

184

def create_loader(options, missing_modules=()): ...

185

class Loader: ...

186

class Module: ...

187

```

188

189

[Module Loading](./module-loading.md)

190

191

## Types

192

193

### Core Analysis Types

194

195

```python { .api }

196

class AnalysisResult:

197

"""Result of PyType analysis operations."""

198

def __init__(self, ast, errors, loader): ...

199

200

class Analysis:

201

"""Analysis context and results."""

202

def __init__(self, context, ast, ast_deps): ...

203

```

204

205

### Configuration Types

206

207

```python { .api }

208

class PostprocessingError(Exception):

209

"""Error during configuration postprocessing."""

210

```

211

212

### Utility Types

213

214

```python { .api }

215

class UsageError(Exception):

216

"""Top-level usage errors."""

217

```