0
# PyObject Manipulation
1
2
Complete PyObject class providing JavaScript interface to Python objects, with methods for property access, method calls, type conversion, and iteration.
3
4
## Capabilities
5
6
### Core Properties
7
8
Read-only properties that provide metadata about the wrapped Python object.
9
10
```typescript { .api }
11
/**
12
* Numeric identifier of the Python object, equivalent to Python id()
13
*/
14
readonly id: number;
15
16
/**
17
* Whether the Python object is callable (function, method, class, etc.)
18
*/
19
readonly callable: boolean;
20
21
/**
22
* String representation of the Python object's type
23
*/
24
readonly type: string;
25
26
/**
27
* Length of the object if it supports len(), undefined otherwise
28
*/
29
readonly length: number | undefined;
30
31
/**
32
* The Python type/constructor of the object, equivalent to type(obj)
33
*/
34
readonly constr: PyObject;
35
```
36
37
### Property Access
38
39
Access Python object attributes and check for their existence.
40
41
```typescript { .api }
42
/**
43
* Get a property from the Python object
44
* @param name - Property name to retrieve
45
* @returns PyObject representing the property value
46
*/
47
get(name: string): PyObject;
48
49
/**
50
* Check if a property exists on the Python object
51
* @param name - Property name to check (for sets, can be any value)
52
* @returns True if the property exists
53
*/
54
has(name: string | any): boolean;
55
```
56
57
**Usage Examples:**
58
59
```javascript
60
const sys = pymport('sys');
61
62
// Get properties
63
const version = sys.get('version');
64
const path = sys.get('path');
65
66
// Check if properties exist
67
console.log(sys.has('version')); // true
68
console.log(sys.has('nonexistent')); // false
69
70
// For sets, check membership
71
const pySet = PyObject.set([1, 2, 3]);
72
console.log(pySet.has(2)); // true
73
console.log(pySet.has(5)); // false
74
```
75
76
### Index Access
77
78
Access Python object elements by index or key, equivalent to Python's subscript operator [].
79
80
```typescript { .api }
81
/**
82
* Retrieve an element by index or key
83
* @param index - Index, key, or slice for element access
84
* @returns PyObject representing the accessed element
85
*/
86
item(index: any): PyObject;
87
```
88
89
**Usage Examples:**
90
91
```javascript
92
const np = proxify(pymport('numpy'));
93
94
// Array indexing
95
const arr = np.array([1, 2, 3, 4, 5]);
96
console.log(arr.item(0).toJS()); // 1
97
console.log(arr.item(-1).toJS()); // 5
98
99
// Dictionary key access
100
const pyDict = PyObject.dict({ a: 1, b: 2 });
101
console.log(pyDict.item('a').toJS()); // 1
102
103
// Slice access
104
const slice = PyObject.slice([1, 4, 1]); // start=1, stop=4, step=1
105
const subarray = arr.item(slice);
106
console.log(subarray.toJS()); // [2, 3, 4]
107
```
108
109
### Function Calls
110
111
Call Python functions and methods with automatic argument conversion.
112
113
```typescript { .api }
114
/**
115
* Call a callable PyObject synchronously
116
* @param args - Arguments to pass to the Python function
117
* @returns PyObject result of the function call
118
* @throws Error if the object is not callable
119
*/
120
call(...args: any[]): PyObject;
121
122
/**
123
* Call a callable PyObject asynchronously
124
* @param args - Arguments to pass to the Python function
125
* @returns Promise resolving to PyObject result
126
* @throws Promise rejection if the object is not callable
127
*/
128
callAsync(...args: any[]): Promise<PyObject>;
129
```
130
131
**Usage Examples:**
132
133
```javascript
134
const np = proxify(pymport('numpy'));
135
136
// Synchronous function calls
137
const array = np.array.call([1, 2, 3, 4]);
138
const sum = np.sum.call(array);
139
140
// Asynchronous function calls (useful for long-running operations)
141
const largeArray = np.random.random.call([1000, 1000]);
142
const asyncSum = await np.sum.callAsync(largeArray);
143
144
// Method calls on objects
145
const reshaped = array.get('reshape').call(2, 2);
146
```
147
148
### Context Management
149
150
Execute code within Python context managers (with statements).
151
152
```typescript { .api }
153
/**
154
* Execute a function within the context of this PyObject
155
* Equivalent to Python's 'with' statement
156
* @param fn - Function to execute with the context object
157
* @returns Result of the function execution
158
*/
159
with<T>(fn: (v: PyObject) => T): T;
160
```
161
162
**Usage Examples:**
163
164
```javascript
165
// File handling with context management
166
const builtins = pymport('builtins');
167
const open = builtins.get('open');
168
169
const file = open.call('example.txt', 'w');
170
file.with((f) => {
171
f.get('write').call('Hello, Python from Node.js!');
172
// File automatically closed when context exits
173
});
174
175
// Custom context managers
176
const contextManager = pyval('some_context_manager()');
177
const result = contextManager.with((ctx) => {
178
// Use the context object
179
return ctx.get('some_method').call();
180
});
181
```
182
183
### Data Conversion
184
185
Convert PyObjects to JavaScript values and vice versa.
186
187
```typescript { .api }
188
/**
189
* Convert PyObject to JavaScript value with configurable options
190
* @param opts - Conversion options
191
* @param opts.depth - Maximum recursion depth (undefined for unlimited)
192
* @param opts.buffer - Whether to convert buffer protocol objects
193
* @returns JavaScript representation of the Python object
194
*/
195
toJS(opts?: { depth?: number; buffer?: boolean; }): any;
196
197
/**
198
* Convert PyObject to JavaScript value (equivalent to toJS())
199
* @returns JavaScript representation of the Python object
200
*/
201
valueOf(): any;
202
203
/**
204
* Get string representation using Python's str() function
205
* @returns String representation of the object
206
*/
207
toString(): string;
208
```
209
210
**Usage Examples:**
211
212
```javascript
213
const np = proxify(pymport('numpy'));
214
215
// Basic conversion
216
const pyArray = np.array([1, 2, 3]);
217
const jsArray = pyArray.toJS();
218
console.log(jsArray); // [1, 2, 3]
219
220
// Controlled depth conversion
221
const nested = np.array([[1, 2], [3, 4]]);
222
const shallow = nested.toJS({ depth: 1 }); // Keep inner arrays as PyObjects
223
const deep = nested.toJS(); // Convert everything to JS
224
225
// String representation
226
console.log(pyArray.toString()); // "[1 2 3]"
227
```
228
229
### Iteration
230
231
Iterate over Python objects that support iteration.
232
233
```typescript { .api }
234
/**
235
* Return an iterator over the object's elements
236
* Works with any Python iterable (lists, tuples, strings, etc.)
237
*/
238
[Symbol.iterator](): Iterator<PyObject>;
239
240
/**
241
* Map function over iterable PyObject elements
242
* @param callback - Function to call for each element
243
* @param thisArg - Optional 'this' context for the callback
244
* @returns Array of mapped results
245
*/
246
map<T, U>(
247
callback: (this: U, element: PyObject, index: number, iterable: PyObject) => T,
248
thisArg?: U
249
): T[];
250
```
251
252
**Usage Examples:**
253
254
```javascript
255
const pyList = PyObject.list([1, 2, 3, 4, 5]);
256
257
// For-of iteration
258
for (const item of pyList) {
259
console.log(item.toJS());
260
}
261
262
// Map over elements
263
const doubled = pyList.map((item, index) => item.toJS() * 2);
264
console.log(doubled); // [2, 4, 6, 8, 10]
265
266
// String iteration
267
const pyString = PyObject.string('hello');
268
const chars = [...pyString].map(char => char.toString());
269
console.log(chars); // ['h', 'e', 'l', 'l', 'o']
270
```
271
272
### Static Utility Methods
273
274
Utility methods for working with Python dictionaries.
275
276
```typescript { .api }
277
/**
278
* Get dictionary keys as a Python list
279
* @param obj - Dictionary PyObject
280
* @returns PyObject list of keys
281
*/
282
static keys(obj: PyObject): PyObject;
283
284
/**
285
* Get dictionary values as a Python list
286
* @param obj - Dictionary PyObject
287
* @returns PyObject list of values
288
*/
289
static values(obj: PyObject): PyObject;
290
```
291
292
**Usage Examples:**
293
294
```javascript
295
const pyDict = PyObject.dict({ a: 1, b: 2, c: 3 });
296
297
// Get keys and values
298
const keys = PyObject.keys(pyDict);
299
const values = PyObject.values(pyDict);
300
301
console.log(keys.toJS()); // ['a', 'b', 'c']
302
console.log(values.toJS()); // [1, 2, 3]
303
304
// Iterate over dictionary items
305
for (const key of keys) {
306
const value = pyDict.item(key.toString());
307
console.log(`${key.toString()}: ${value.toJS()}`);
308
}
309
```