or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

error-handling.mdindex.mdobject-creation.mdpyobject.mdpython-modules.mdtype-conversion.md

type-conversion.mddocs/

0

# Type Conversion & Interoperability

1

2

Advanced type conversion capabilities between Python and JavaScript, including specialized typed array handling, buffer protocol support, and proxified alternatives.

3

4

## Capabilities

5

6

### Typed Array Conversion

7

8

Convert between Python array.array objects and JavaScript TypedArrays with automatic type mapping.

9

10

```typescript { .api }

11

/**

12

* Get the JavaScript TypedArray constructor for a Python array.array object

13

* @param array - Python array.array PyObject

14

* @returns TypedArray constructor (Uint8Array, Float32Array, etc.)

15

*/

16

function getJSType(array: PyObject): TypedArrayConstructor;

17

18

/**

19

* Get the Python array.array type code for a JavaScript TypedArray

20

* @param array - JavaScript TypedArray

21

* @returns Python array type code string ('b', 'i', 'f', etc.)

22

*/

23

function getPythonType(array: TypedArray): string;

24

25

/**

26

* Convert Python array.array to JavaScript TypedArray (contents copied)

27

* @param array - Python array.array PyObject

28

* @returns Corresponding JavaScript TypedArray

29

*/

30

function toTypedArray(array: PyObject): TypedArray;

31

32

/**

33

* Convert JavaScript TypedArray to Python array.array (contents copied)

34

* @param array - JavaScript TypedArray

35

* @returns Python array.array PyObject

36

*/

37

function toPythonArray(array: TypedArray): PyObject;

38

```

39

40

**Usage Examples:**

41

42

```javascript

43

import { toTypedArray, toPythonArray, getJSType, getPythonType } from 'pymport/array';

44

45

// Create Python array

46

const array_module = pymport('array');

47

const pyArray = array_module.get('array').call('f', [1.1, 2.2, 3.3, 4.4]);

48

49

// Convert to JavaScript TypedArray

50

const jsArray = toTypedArray(pyArray);

51

console.log(jsArray); // Float32Array [1.1, 2.2, 3.3, 4.4]

52

console.log(jsArray.constructor.name); // "Float32Array"

53

54

// Get type information

55

const JSType = getJSType(pyArray);

56

console.log(JSType.name); // "Float32Array"

57

58

// Convert JavaScript TypedArray to Python

59

const uint32Array = new Uint32Array([1, 2, 3, 4]);

60

const pyArray2 = toPythonArray(uint32Array);

61

console.log(getPythonType(uint32Array)); // "I" (unsigned int)

62

63

// Type mappings:

64

// 'b' → Int8Array

65

// 'B' → Uint8Array

66

// 'h' → Int16Array

67

// 'H' → Uint16Array

68

// 'i' → Int32Array

69

// 'I' → Uint32Array

70

// 'l' → Int32Array or BigInt64Array (platform dependent)

71

// 'L' → Uint32Array or BigUint64Array (platform dependent)

72

// 'q' → BigInt64Array

73

// 'Q' → BigUint64Array

74

// 'f' → Float32Array

75

// 'd' → Float64Array

76

```

77

78

### Python Code Evaluation

79

80

Execute Python expressions with full context control for dynamic code execution.

81

82

```typescript { .api }

83

/**

84

* Evaluate Python code with optional global and local contexts

85

* @param code - Python expression string (not statements)

86

* @param globals - Global context (PyObject dict or JS object)

87

* @param locals - Local context (PyObject dict or JS object)

88

* @returns PyObject result of the evaluation

89

*/

90

function pyval(

91

code: string,

92

globals?: PyObject | Record<string, any>,

93

locals?: PyObject | Record<string, any>

94

): PyObject;

95

```

96

97

**Usage Examples:**

98

99

```javascript

100

import { pyval, pymport } from 'pymport';

101

102

// Basic mathematical expressions

103

const result1 = pyval('2 ** 10');

104

console.log(result1.toJS()); // 1024

105

106

const result2 = pyval('abs(-42) + max([1, 5, 3])');

107

console.log(result2.toJS()); // 47

108

109

// Using imported modules

110

const np = pymport('numpy');

111

const globals = { np, x: [1, 2, 3, 4, 5] };

112

const array_result = pyval('np.array(x) * 2', globals);

113

console.log(array_result.toJS()); // [2, 4, 6, 8, 10]

114

115

// Complex expressions with local variables

116

const math = pymport('math');

117

const context = {

118

math,

119

radius: 5

120

};

121

const area = pyval('math.pi * radius ** 2', context);

122

console.log(area.toJS()); // ~78.54

123

124

// String operations

125

const text_result = pyval('"hello".upper() + " " + "world".title()');

126

console.log(text_result.toJS()); // "HELLO World"

127

```

128

129

### Proxified Module System

130

131

Use proxified versions of core pymport functions that automatically return proxified objects.

132

133

```typescript { .api }

134

/**

135

* Proxified PyObject class that creates proxified objects

136

*/

137

const PyObject: typeof rawPyObject & any;

138

139

/**

140

* Proxified pymport function that returns proxified modules

141

* @param mod - Python module name

142

* @returns Proxified Python module

143

*/

144

const pymport: (mod: string) => any;

145

146

/**

147

* Proxified pyval function that returns proxified results

148

* @param code - Python expression string

149

* @param globals - Global context

150

* @param locals - Local context

151

* @returns Proxified PyObject result

152

*/

153

function pyval(

154

code: string,

155

globals?: typeof PyObject | Record<string, any>,

156

locals?: typeof PyObject | Record<string, any>

157

): any;

158

```

159

160

**Usage Examples:**

161

162

```javascript

163

// Import proxified versions

164

import { pymport, pyval, PyObject } from 'pymport/proxified';

165

166

// All results are automatically proxified

167

const np = pymport('numpy'); // Already proxified

168

const array = np.arange(12).reshape(3, 4); // Natural syntax

169

const sum = array.sum(); // No .get() needed

170

171

// Proxified pyval

172

const result = pyval('list(range(5))'); // Returns proxified list

173

console.log(result[2]); // Access like JS array: 2

174

175

// Proxified object creation

176

const pyList = PyObject.list([1, 2, 3]);

177

console.log(pyList.append); // Direct method access

178

pyList.append(4); // Natural method call

179

```

180

181

### Buffer Protocol Support

182

183

Handle Python objects that implement the buffer protocol (bytes, bytearray, memoryview) with automatic Buffer conversion.

184

185

```typescript { .api }

186

// From PyObject.toJS() conversion options

187

interface ConversionOptions {

188

/**

189

* Maximum recursion depth for nested objects

190

* undefined = unlimited depth

191

*/

192

depth?: number;

193

194

/**

195

* Whether to convert buffer protocol objects to Node.js Buffers

196

* true = convert to Buffer (default)

197

* false = keep as PyObject

198

*/

199

buffer?: boolean;

200

}

201

```

202

203

**Usage Examples:**

204

205

```javascript

206

// Python bytes/bytearray to Buffer conversion

207

const pyBytes = PyObject.bytes(Buffer.from('Hello'));

208

const pyBytearray = PyObject.bytearray(Buffer.from('World'));

209

210

// Automatic Buffer conversion (default)

211

const buffer1 = pyBytes.toJS(); // Node.js Buffer

212

const buffer2 = pyBytearray.toJS(); // Node.js Buffer

213

214

// Keep as PyObject

215

const pyObj1 = pyBytes.toJS({ buffer: false }); // Still PyObject

216

const pyObj2 = pyBytearray.toJS({ buffer: false }); // Still PyObject

217

218

// Memory view handling

219

const originalBuffer = Buffer.from('Shared Memory');

220

const memView = PyObject.memoryview(originalBuffer);

221

222

// Memoryview references original buffer

223

const sharedBuffer = memView.toJS();

224

originalBuffer[0] = 65; // Modify original

225

console.log(sharedBuffer[0]); // 65 (reflects change)

226

```

227

228

### Complex Type Conversions

229

230

Handle complex nested structures with configurable conversion depth.

231

232

**Usage Examples:**

233

234

```javascript

235

const np = proxify(pymport('numpy'));

236

237

// Create complex nested structure

238

const nested = {

239

arrays: [

240

np.array([1, 2, 3]),

241

np.array([[4, 5], [6, 7]])

242

],

243

metadata: {

244

shape: np.array([2, 2]),

245

dtype: np.float64

246

}

247

};

248

249

const pyNested = PyObject.fromJS(nested);

250

251

// Full conversion (unlimited depth)

252

const fullJS = pyNested.toJS();

253

console.log(fullJS.arrays[0]); // [1, 2, 3] (JS array)

254

255

// Shallow conversion (depth=1)

256

const shallow = pyNested.toJS({ depth: 1 });

257

console.log(shallow.arrays[0].toJS); // Still PyObject (function exists)

258

259

// Intermediate depth

260

const intermediate = pyNested.toJS({ depth: 2 });

261

console.log(intermediate.arrays); // JS array

262

console.log(intermediate.arrays[0].toJS); // Still PyObject

263

```

264

265

### Error Context in Conversions

266

267

Type conversion errors include full Python traceback information.

268

269

**Usage Examples:**

270

271

```javascript

272

try {

273

// This will fail - can't convert incompatible types

274

const badConversion = pyval('object()').toJS();

275

} catch (error) {

276

if (error.pythonTrace) {

277

console.log('Python Error Type:', error.pythonType.toString());

278

console.log('Python Value:', error.pythonValue.toString());

279

console.log('Python Traceback:', error.pythonTrace.toString());

280

}

281

}

282

283

try {

284

// Invalid Python syntax

285

const invalid = pyval('2 +'); // Incomplete expression

286

} catch (error) {

287

console.log('Syntax Error:', error.message);

288

}

289

```

290

291

## Type Definitions

292

293

Complete type definitions for the array conversion module:

294

295

```typescript { .api }

296

type TypedArray = Uint8Array | Int8Array | Uint16Array | Int16Array |

297

Uint32Array | Int32Array | BigUint64Array | BigInt64Array |

298

Float32Array | Float64Array;

299

300

type TypedArrayConstructor =

301

typeof Uint8Array | typeof Int8Array | typeof Uint16Array | typeof Int16Array |

302

typeof Uint32Array | typeof Int32Array | typeof BigUint64Array | typeof BigInt64Array |

303

typeof Float32Array | typeof Float64Array;

304

305

interface ConversionOptions {

306

depth?: number;

307

buffer?: boolean;

308

}

309

```