or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

environment-reporting.mdimport-tracking.mdindex.mdutilities.md

import-tracking.mddocs/

0

# Import Tracking

1

2

Track all imports during a Python session and generate reports based on the actually imported packages. This is useful for discovering the real dependencies of a script or notebook session.

3

4

## Capabilities

5

6

### Import Tracking Functions

7

8

Control the import tracking system to monitor all package imports during execution.

9

10

```python { .api }

11

def track_imports() -> None:

12

"""

13

Start tracking all imported modules for the remainder of this session.

14

15

This function replaces the built-in __import__ function with a tracking

16

version that records all non-standard library packages that are imported.

17

18

Raises:

19

RuntimeError: If tracking is not supported (Python version too old)

20

"""

21

22

def untrack_imports() -> None:

23

"""

24

Stop tracking imports and return to the builtin import method.

25

26

This will also clear the tracked imports list, resetting it to only

27

contain 'scooby'.

28

29

Raises:

30

RuntimeError: If tracking is not supported (Python version too old)

31

"""

32

```

33

34

### TrackedReport Class

35

36

Generate environment reports based on the packages that were actually imported during the session.

37

38

```python { .api }

39

class TrackedReport(Report):

40

def __init__(

41

self,

42

additional: list[str | ModuleType] | None = None,

43

ncol: int = 3,

44

text_width: int = 80,

45

sort: bool = False

46

):

47

"""

48

Generate a report based on tracked imports.

49

50

Parameters:

51

- additional (list[str | ModuleType], optional): Additional packages to include beyond tracked imports

52

- ncol (int): Number of columns in HTML table, default: 3

53

- text_width (int): Text width for plain text output, default: 80

54

- sort (bool): Sort packages alphabetically, default: False

55

56

Raises:

57

RuntimeError: If tracking is not supported or no imports have been tracked

58

"""

59

```

60

61

## Usage Examples

62

63

### Basic Import Tracking

64

65

```python

66

import scooby

67

68

# Start tracking imports

69

scooby.track_imports()

70

71

# Import packages during your work

72

import numpy as np

73

import pandas as pd

74

from matplotlib import pyplot as plt

75

import requests

76

77

# Generate report based on tracked imports

78

report = scooby.TrackedReport()

79

print(report)

80

81

# Stop tracking and clear the list

82

scooby.untrack_imports()

83

```

84

85

### Tracking with Additional Packages

86

87

```python

88

import scooby

89

90

# Start tracking

91

scooby.track_imports()

92

93

# Do some work that imports packages

94

import json # Standard library - won't be tracked

95

import numpy

96

from scipy import stats

97

import custom_local_module # Local modules may not be tracked

98

99

# Generate report with additional packages beyond tracked ones

100

report = scooby.TrackedReport(

101

additional=['psutil', 'mkl'], # Add packages not imported but relevant

102

sort=True

103

)

104

print(report)

105

106

# Clean up tracking

107

scooby.untrack_imports()

108

```

109

110

### Session-based Analysis

111

112

```python

113

import scooby

114

115

# Track imports for analysis session

116

scooby.track_imports()

117

118

# Simulate a data analysis workflow

119

import pandas as pd

120

import numpy as np

121

import matplotlib.pyplot as plt

122

import seaborn as sns

123

from sklearn.model_selection import train_test_split

124

from sklearn.ensemble import RandomForestClassifier

125

126

# Some work happens here...

127

data = pd.read_csv('data.csv')

128

# ... analysis code ...

129

130

# Generate report showing what was actually used

131

report = scooby.TrackedReport()

132

print("Packages used in this analysis:")

133

print(report)

134

135

# Stop tracking

136

scooby.untrack_imports()

137

```

138

139

### Jupyter Notebook Usage

140

141

```python

142

# In first cell

143

import scooby

144

scooby.track_imports()

145

146

# In various cells throughout the notebook

147

import numpy as np

148

import pandas as pd

149

# ... other imports as needed ...

150

151

# In final cell - see what was actually imported

152

report = scooby.TrackedReport()

153

display(report) # Shows HTML in Jupyter

154

155

# Clean up

156

scooby.untrack_imports()

157

```

158

159

### Context Manager Pattern

160

161

```python

162

import scooby

163

164

class ImportTracker:

165

def __enter__(self):

166

scooby.track_imports()

167

return self

168

169

def __exit__(self, exc_type, exc_val, exc_tb):

170

scooby.untrack_imports()

171

172

def report(self):

173

return scooby.TrackedReport()

174

175

# Use with context manager

176

with ImportTracker() as tracker:

177

import numpy

178

import pandas

179

# ... do work ...

180

181

# Generate report within the tracking context

182

report = tracker.report()

183

print(report)

184

# Tracking automatically stopped

185

```

186

187

## Important Notes

188

189

### Tracking Limitations

190

191

- **Python Version**: Import tracking requires modern Python versions. Older versions will raise `RuntimeError`.

192

- **Standard Library**: Standard library modules are automatically excluded from tracking.

193

- **Module Filtering**: Some modules are excluded by default (e.g., internal modules starting with `_`, certain system modules).

194

- **Import Timing**: Only tracks imports that happen *after* `track_imports()` is called.

195

196

### Best Practices

197

198

```python

199

import scooby

200

201

# Always use try/finally or context managers to ensure cleanup

202

scooby.track_imports()

203

try:

204

# ... your code with imports ...

205

report = scooby.TrackedReport()

206

print(report)

207

finally:

208

scooby.untrack_imports()

209

```

210

211

### Error Handling

212

213

```python

214

import scooby

215

216

try:

217

scooby.track_imports()

218

except RuntimeError as e:

219

print(f"Tracking not supported: {e}")

220

# Fall back to regular Report

221

report = scooby.Report()

222

else:

223

# ... do tracked work ...

224

try:

225

report = scooby.TrackedReport()

226

except RuntimeError as e:

227

print(f"No tracked imports: {e}")

228

report = scooby.Report()

229

finally:

230

scooby.untrack_imports()

231

232

print(report)

233

```