or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

code-navigation.mdcode-refactoring.mdconfiguration.mdenvironment-management.mdindex.mdinterpreter-integration.mdproject-configuration.mdscript-analysis.md

interpreter-integration.mddocs/

0

# Interpreter Integration

1

2

REPL and interactive environment support with runtime namespace integration. The Interpreter class extends Script functionality to work with actual runtime objects and namespaces, enabling completions and analysis in interactive Python sessions.

3

4

## Capabilities

5

6

### Interpreter Creation

7

8

Initialize interpreter analysis with runtime namespaces for REPL environments.

9

10

```python { .api }

11

class Interpreter(Script):

12

def __init__(self, code, namespaces, *, project=None, **kwds):

13

"""

14

Create an Interpreter for REPL analysis.

15

16

Parameters:

17

- code (str): Code to analyze.

18

- namespaces (list): List of namespace dictionaries (globals(), locals(), etc.).

19

- project (Project, optional): Project configuration.

20

- **kwds: Additional keyword arguments passed to Script.

21

"""

22

```

23

24

**Usage Example:**

25

```python

26

import jedi

27

28

# Basic interpreter usage

29

namespace = {'x': 42, 'y': [1, 2, 3]}

30

interpreter = jedi.Interpreter('x.', [namespace])

31

completions = interpreter.complete()

32

33

# With multiple namespaces

34

global_ns = globals()

35

local_ns = {'custom_var': 'hello'}

36

interpreter = jedi.Interpreter('custom_var.', [global_ns, local_ns])

37

38

# In an IPython/Jupyter context

39

def get_completions(code, cursor_pos):

40

namespaces = [get_ipython().user_ns, get_ipython().user_global_ns]

41

interpreter = jedi.Interpreter(code, namespaces)

42

return interpreter.complete(cursor_pos)

43

```

44

45

### Runtime Object Analysis

46

47

Analyze objects that exist in the runtime environment, providing accurate type information and completions based on actual object state.

48

49

**Usage Example:**

50

```python

51

import jedi

52

import pandas as pd

53

54

# Create runtime objects

55

df = pd.DataFrame({'A': [1, 2, 3], 'B': ['x', 'y', 'z']})

56

namespace = {'df': df, 'pd': pd}

57

58

# Get completions for actual DataFrame object

59

interpreter = jedi.Interpreter('df.', [namespace])

60

completions = interpreter.complete()

61

62

for completion in completions:

63

print(f"{completion.name}: {completion.type}")

64

65

# Analyze method signatures with actual object

66

interpreter = jedi.Interpreter('df.groupby(', [namespace])

67

signatures = interpreter.get_signatures()

68

for sig in signatures:

69

print(f"Method: {sig.name}")

70

for param in sig.params:

71

print(f" {param.name}: {param.description}")

72

```

73

74

### Interactive Session Support

75

76

Support for interactive Python sessions, REPLs, and notebook environments with dynamic namespace tracking.

77

78

**Usage Example:**

79

```python

80

# Simulating an interactive session

81

import jedi

82

83

class InteractiveSession:

84

def __init__(self):

85

self.namespace = {}

86

87

def execute(self, code):

88

exec(code, self.namespace)

89

90

def get_completions(self, code):

91

interpreter = jedi.Interpreter(code, [self.namespace])

92

return interpreter.complete()

93

94

# Usage

95

session = InteractiveSession()

96

session.execute("import json")

97

session.execute("data = {'key': 'value'}")

98

99

# Get completions with current session state

100

completions = session.get_completions("json.")

101

for c in completions:

102

print(c.name)

103

104

completions = session.get_completions("data.")

105

for c in completions:

106

print(c.name)

107

```

108

109

### REPL Integration Patterns

110

111

Common patterns for integrating jedi with different REPL environments.

112

113

**IPython Integration:**

114

```python

115

from IPython import get_ipython

116

import jedi

117

118

def jedi_completions(text, line, cursor_pos):

119

"""Custom IPython completer using jedi."""

120

ip = get_ipython()

121

namespaces = [ip.user_ns, ip.user_global_ns]

122

123

interpreter = jedi.Interpreter(text, namespaces)

124

completions = interpreter.complete()

125

126

return [c.name for c in completions]

127

128

# Register with IPython

129

get_ipython().set_custom_completer(jedi_completions)

130

```

131

132

**Code.InteractiveConsole Integration:**

133

```python

134

import code

135

import jedi

136

137

class JediConsole(code.InteractiveConsole):

138

def __init__(self, locals=None):

139

super().__init__(locals)

140

self.jedi_locals = locals or {}

141

142

def get_completions(self, text):

143

namespaces = [self.jedi_locals, __builtins__]

144

interpreter = jedi.Interpreter(text, namespaces)

145

return [c.name for c in interpreter.complete()]

146

147

# Usage

148

console = JediConsole({'myvar': 42})

149

console.interact()

150

```

151

152

### Namespace Management

153

154

Handle multiple namespaces and namespace precedence for accurate analysis.

155

156

```python { .api }

157

class Interpreter:

158

namespaces: list # List of namespace dictionaries

159

```

160

161

**Usage Example:**

162

```python

163

import jedi

164

165

# Multiple namespace levels

166

builtins_ns = __builtins__

167

global_ns = globals()

168

local_ns = {'local_var': 'local_value'}

169

custom_ns = {'custom_func': lambda x: x * 2}

170

171

# Namespace precedence: later namespaces override earlier ones

172

namespaces = [builtins_ns, global_ns, local_ns, custom_ns]

173

174

interpreter = jedi.Interpreter('local_var.', namespaces)

175

completions = interpreter.complete()

176

177

# Check what namespace a completion comes from

178

for completion in completions:

179

definitions = completion.goto()

180

for definition in definitions:

181

print(f"{completion.name} defined in: {definition.module_path}")

182

```

183

184

### Dynamic Execution Analysis

185

186

Analyze code with dynamic execution capabilities for descriptor evaluation and property access.

187

188

**Configuration:**

189

```python

190

import jedi

191

192

# Control dynamic execution behavior

193

jedi.settings.allow_unsafe_interpreter_executions = True # Default: True

194

195

# This allows jedi to evaluate descriptors and properties

196

class MyClass:

197

@property

198

def dynamic_prop(self):

199

return "computed value"

200

201

obj = MyClass()

202

namespace = {'obj': obj}

203

204

interpreter = jedi.Interpreter('obj.dynamic_prop.', [namespace])

205

completions = interpreter.complete() # Can access string methods

206

```

207

208

## Interpreter-Specific Considerations

209

210

### Safety and Security

211

212

The Interpreter can execute code through descriptor evaluation. Control this behavior through settings:

213

214

```python

215

import jedi

216

217

# Disable potentially unsafe executions

218

jedi.settings.allow_unsafe_interpreter_executions = False

219

220

# This affects property and descriptor evaluation

221

class UnsafeClass:

222

@property

223

def dangerous_prop(self):

224

# This won't be evaluated if unsafe executions are disabled

225

return os.system("rm -rf /")

226

227

obj = UnsafeClass()

228

interpreter = jedi.Interpreter('obj.dangerous_prop.', [{'obj': obj}])

229

```

230

231

### Performance Considerations

232

233

Interpreter analysis may be slower than Script analysis due to runtime object inspection:

234

235

```python

236

import jedi

237

238

# For better performance in REPL environments

239

jedi.settings.call_signatures_validity = 3.0 # Cache signatures for 3 seconds

240

241

# Preload commonly used modules

242

jedi.preload_module('json', 'os', 'sys', 'collections')

243

244

# Use environment-specific settings

245

interpreter = jedi.Interpreter(

246

code,

247

namespaces,

248

environment=jedi.api.environment.InterpreterEnvironment()

249

)

250

```