0
# Python Object Operations
1
2
Comprehensive API for creating, manipulating, and managing Python objects from Java. This covers all major Python types including lists, dictionaries, strings, numbers, and advanced object operations like reference counting and type checking.
3
4
## Capabilities
5
6
### Reference Counting and Object Management
7
8
Core functions for managing Python object lifetimes and reference counting.
9
10
```java { .api }
11
/**
12
* Get reference count of a Python object
13
* @param ob - Python object
14
* @return Current reference count
15
*/
16
public static native long Py_REFCNT(PyObject ob);
17
18
/**
19
* Set reference count of a Python object
20
* @param ob - Python object
21
* @param refcnt - New reference count
22
*/
23
public static native void Py_SET_REFCNT(PyObject ob, long refcnt);
24
25
/**
26
* Set reference count (internal version)
27
* @param ob - Python object
28
* @param refcnt - New reference count
29
*/
30
public static native void _Py_SetRefcnt(PyObject ob, long refcnt);
31
32
/**
33
* Check if object is immortal (never deallocated)
34
* @param op - Python object
35
* @return Non-zero if object is immortal
36
*/
37
public static native int _Py_IsImmortal(PyObject op);
38
```
39
40
### Object Identity and Type Operations
41
42
Functions for checking object identity, types, and basic properties.
43
44
```java { .api }
45
/**
46
* Test object identity (equivalent to Python 'is' operator)
47
* @param x - First object
48
* @param y - Second object
49
* @return Non-zero if objects are identical
50
*/
51
public static native int Py_Is(PyObject x, PyObject y);
52
53
/**
54
* Get type of a Python object
55
* @param ob - Python object
56
* @return Type object
57
*/
58
public static native PyTypeObject Py_TYPE(PyObject ob);
59
60
/**
61
* Check if object is of specific type
62
* @param ob - Python object
63
* @param type - Type to check against
64
* @return Non-zero if object is of specified type
65
*/
66
public static native int Py_IS_TYPE(PyObject ob, PyTypeObject type);
67
68
/**
69
* Set type of a Python object
70
* @param ob - Python object
71
* @param type - New type
72
*/
73
public static native void Py_SET_TYPE(PyObject ob, PyTypeObject type);
74
75
/**
76
* Get size of variable-length object
77
* @param ob - Python object
78
* @return Size of object
79
*/
80
public static native long Py_SIZE(PyObject ob);
81
82
/**
83
* Set size of variable-length object
84
* @param ob - Python variable object
85
* @param size - New size
86
*/
87
public static native void Py_SET_SIZE(PyVarObject ob, long size);
88
```
89
90
### Generic Object Operations
91
92
Universal operations that work on all Python objects.
93
94
```java { .api }
95
/**
96
* Compute hash value of an object
97
* @param obj - Python object
98
* @return Hash value, or -1 on error
99
*/
100
public static native long PyObject_Hash(PyObject obj);
101
102
/**
103
* Enter recursive representation (for avoiding infinite recursion in repr)
104
* @param obj - Python object
105
* @return 0 on success, 1 if already entered, -1 on error
106
*/
107
public static native int Py_ReprEnter(PyObject obj);
108
109
/**
110
* Leave recursive representation
111
* @param obj - Python object
112
*/
113
public static native void Py_ReprLeave(PyObject obj);
114
```
115
116
**Usage Example:**
117
118
```java
119
import static org.bytedeco.cpython.global.python.*;
120
121
// Create an object and check its properties
122
PyObject obj = PyUnicode_FromString("Hello");
123
124
// Get reference count
125
long refCount = Py_REFCNT(obj);
126
127
// Get type
128
PyTypeObject type = Py_TYPE(obj);
129
130
// Compute hash
131
long hash = PyObject_Hash(obj);
132
133
// Check if it's a string type
134
int isString = Py_IS_TYPE(obj, type);
135
```
136
137
### List Operations
138
139
Complete API for working with Python lists.
140
141
```java { .api }
142
/**
143
* Create new list with specified size
144
* @param size - Initial size of list
145
* @return New list object
146
*/
147
public static native PyObject PyList_New(long size);
148
149
/**
150
* Get size of list
151
* @param list - List object
152
* @return Size of list, or -1 on error
153
*/
154
public static native long PyList_Size(PyObject list);
155
156
/**
157
* Get item at index (borrowed reference)
158
* @param list - List object
159
* @param index - Index of item
160
* @return Item at index, or NULL on error
161
*/
162
public static native PyObject PyList_GetItem(PyObject list, long index);
163
164
/**
165
* Get item at index (new reference)
166
* @param list - List object
167
* @param index - Index of item
168
* @return New reference to item at index, or NULL on error
169
*/
170
public static native PyObject PyList_GetItemRef(PyObject list, long index);
171
172
/**
173
* Set item at index
174
* @param list - List object
175
* @param index - Index to set
176
* @param item - Item to set
177
* @return 0 on success, -1 on error
178
*/
179
public static native int PyList_SetItem(PyObject list, long index, PyObject item);
180
181
/**
182
* Insert item at index
183
* @param list - List object
184
* @param index - Index to insert at
185
* @param item - Item to insert
186
* @return 0 on success, -1 on error
187
*/
188
public static native int PyList_Insert(PyObject list, long index, PyObject item);
189
190
/**
191
* Append item to end of list
192
* @param list - List object
193
* @param item - Item to append
194
* @return 0 on success, -1 on error
195
*/
196
public static native int PyList_Append(PyObject list, PyObject item);
197
198
/**
199
* Extend list with items from iterable
200
* @param self - List object
201
* @param iterable - Iterable to extend with
202
* @return 0 on success, -1 on error
203
*/
204
public static native int PyList_Extend(PyObject self, PyObject iterable);
205
206
/**
207
* Clear all items from list
208
* @param self - List object
209
* @return 0 on success, -1 on error
210
*/
211
public static native int PyList_Clear(PyObject self);
212
```
213
214
### List Slicing and Advanced Operations
215
216
```java { .api }
217
/**
218
* Get slice of list
219
* @param list - List object
220
* @param low - Start index (inclusive)
221
* @param high - End index (exclusive)
222
* @return New list containing slice
223
*/
224
public static native PyObject PyList_GetSlice(PyObject list, long low, long high);
225
226
/**
227
* Set slice of list
228
* @param list - List object
229
* @param low - Start index (inclusive)
230
* @param high - End index (exclusive)
231
* @param itemlist - List of items to set (or NULL to delete)
232
* @return 0 on success, -1 on error
233
*/
234
public static native int PyList_SetSlice(PyObject list, long low, long high, PyObject itemlist);
235
236
/**
237
* Sort list in place
238
* @param list - List object
239
* @return 0 on success, -1 on error
240
*/
241
public static native int PyList_Sort(PyObject list);
242
243
/**
244
* Reverse list in place
245
* @param list - List object
246
* @return 0 on success, -1 on error
247
*/
248
public static native int PyList_Reverse(PyObject list);
249
250
/**
251
* Convert list to tuple
252
* @param list - List object
253
* @return New tuple containing list items
254
*/
255
public static native PyObject PyList_AsTuple(PyObject list);
256
```
257
258
### Fast List Macros (No Error Checking)
259
260
```java { .api }
261
/**
262
* Get size of list (no error checking)
263
* @param op - List object
264
* @return Size of list
265
*/
266
public static native long PyList_GET_SIZE(PyObject op);
267
268
/**
269
* Set item in list (no error checking, steals reference)
270
* @param op - List object
271
* @param index - Index to set
272
* @param value - Value to set
273
*/
274
public static native void PyList_SET_ITEM(PyObject op, long index, PyObject value);
275
```
276
277
**Usage Example:**
278
279
```java
280
// Create and manipulate a list
281
PyObject list = PyList_New(0);
282
283
// Add items
284
PyObject item1 = PyUnicode_FromString("Hello");
285
PyObject item2 = PyUnicode_FromString("World");
286
PyList_Append(list, item1);
287
PyList_Append(list, item2);
288
289
// Get list size
290
long size = PyList_Size(list); // Returns 2
291
292
// Access items
293
PyObject first = PyList_GetItem(list, 0); // "Hello"
294
295
// Create slice
296
PyObject slice = PyList_GetSlice(list, 0, 1); // ["Hello"]
297
298
// Sort the list
299
PyList_Sort(list);
300
```
301
302
### Dictionary Operations
303
304
Complete API for working with Python dictionaries.
305
306
```java { .api }
307
/**
308
* Create new empty dictionary
309
* @return New dictionary object
310
*/
311
public static native PyObject PyDict_New();
312
313
/**
314
* Get item from dictionary (borrowed reference)
315
* @param dict - Dictionary object
316
* @param key - Key to look up
317
* @return Value for key, or NULL if not found (no exception set)
318
*/
319
public static native PyObject PyDict_GetItem(PyObject dict, PyObject key);
320
321
/**
322
* Get item from dictionary with error reporting
323
* @param dict - Dictionary object
324
* @param key - Key to look up
325
* @return Value for key, or NULL on error or if not found
326
*/
327
public static native PyObject PyDict_GetItemWithError(PyObject dict, PyObject key);
328
329
/**
330
* Get item using string key
331
* @param dict - Dictionary object
332
* @param key - String key
333
* @return Value for key, or NULL if not found
334
*/
335
public static native PyObject PyDict_GetItemString(PyObject dict, String key);
336
337
/**
338
* Set item in dictionary
339
* @param dict - Dictionary object
340
* @param key - Key object
341
* @param item - Value to set
342
* @return 0 on success, -1 on error
343
*/
344
public static native int PyDict_SetItem(PyObject dict, PyObject key, PyObject item);
345
346
/**
347
* Delete item from dictionary
348
* @param dict - Dictionary object
349
* @param key - Key to delete
350
* @return 0 on success, -1 on error
351
*/
352
public static native int PyDict_DelItem(PyObject dict, PyObject key);
353
```
354
355
### Dictionary Inspection and Modification
356
357
```java { .api }
358
/**
359
* Clear all items from dictionary
360
* @param dict - Dictionary object
361
*/
362
public static native void PyDict_Clear(PyObject dict);
363
364
/**
365
* Get size of dictionary
366
* @param dict - Dictionary object
367
* @return Number of items in dictionary
368
*/
369
public static native long PyDict_Size(PyObject dict);
370
371
/**
372
* Check if dictionary contains key
373
* @param dict - Dictionary object
374
* @param key - Key to check for
375
* @return 1 if present, 0 if not present, -1 on error
376
*/
377
public static native int PyDict_Contains(PyObject dict, PyObject key);
378
379
/**
380
* Create shallow copy of dictionary
381
* @param dict - Dictionary to copy
382
* @return New dictionary copy
383
*/
384
public static native PyObject PyDict_Copy(PyObject dict);
385
```
386
387
### Dictionary Views and Iteration
388
389
```java { .api }
390
/**
391
* Get dictionary keys view
392
* @param dict - Dictionary object
393
* @return Keys view object
394
*/
395
public static native PyObject PyDict_Keys(PyObject dict);
396
397
/**
398
* Get dictionary values view
399
* @param dict - Dictionary object
400
* @return Values view object
401
*/
402
public static native PyObject PyDict_Values(PyObject dict);
403
404
/**
405
* Get dictionary items view
406
* @param dict - Dictionary object
407
* @return Items view object
408
*/
409
public static native PyObject PyDict_Items(PyObject dict);
410
411
/**
412
* Iterate over dictionary items
413
* @param dict - Dictionary object
414
* @param pos - Position pointer (modified during iteration)
415
* @param key - Pointer to receive key
416
* @param value - Pointer to receive value
417
* @return 1 if item retrieved, 0 if iteration complete
418
*/
419
public static native int PyDict_Next(PyObject dict, SizeTPointer pos,
420
PointerPointer key, PointerPointer value);
421
```
422
423
### Dictionary Merging
424
425
```java { .api }
426
/**
427
* Update dictionary with items from another mapping
428
* @param dict - Dictionary to update
429
* @param other - Mapping to update from
430
* @return 0 on success, -1 on error
431
*/
432
public static native int PyDict_Update(PyObject dict, PyObject other);
433
434
/**
435
* Merge dictionary with another mapping
436
* @param dict - Dictionary to merge into
437
* @param other - Mapping to merge from
438
* @param override - If non-zero, override existing keys
439
* @return 0 on success, -1 on error
440
*/
441
public static native int PyDict_Merge(PyObject dict, PyObject other, int override);
442
443
/**
444
* Merge dictionary with sequence of key-value pairs
445
* @param dict - Dictionary to merge into
446
* @param seq2 - Sequence of key-value pairs
447
* @param override - If non-zero, override existing keys
448
* @return 0 on success, -1 on error
449
*/
450
public static native int PyDict_MergeFromSeq2(PyObject dict, PyObject seq2, int override);
451
```
452
453
**Usage Example:**
454
455
```java
456
// Create and populate dictionary
457
PyObject dict = PyDict_New();
458
459
// Add items
460
PyObject key1 = PyUnicode_FromString("name");
461
PyObject value1 = PyUnicode_FromString("John");
462
PyDict_SetItem(dict, key1, value1);
463
464
// Add with string key
465
PyDict_SetItemString(dict, "age", PyLong_FromLong(30));
466
467
// Check if key exists
468
int hasName = PyDict_Contains(dict, key1); // Returns 1
469
470
// Get dictionary size
471
long size = PyDict_Size(dict); // Returns 2
472
473
// Iterate over items
474
SizeTPointer pos = new SizeTPointer(1);
475
pos.put(0);
476
PointerPointer keyPtr = new PointerPointer(1);
477
PointerPointer valuePtr = new PointerPointer(1);
478
479
while (PyDict_Next(dict, pos, keyPtr, valuePtr) != 0) {
480
PyObject key = new PyObject(keyPtr.get());
481
PyObject value = new PyObject(valuePtr.get());
482
// Process key-value pair
483
}
484
```
485
486
### String/Unicode Operations
487
488
Comprehensive string handling for Python Unicode objects.
489
490
```java { .api }
491
/**
492
* Create Unicode string from C string
493
* @param str - Null-terminated C string
494
* @return New Unicode object
495
*/
496
public static native PyObject PyUnicode_FromString(String str);
497
498
/**
499
* Create Unicode string from C string with size
500
* @param str - C string (may contain null bytes)
501
* @param size - Length of string
502
* @return New Unicode object
503
*/
504
public static native PyObject PyUnicode_FromStringAndSize(String str, long size);
505
506
/**
507
* Create Unicode from wide character string
508
* @param w - Wide character string
509
* @param size - Length of string
510
* @return New Unicode object
511
*/
512
public static native PyObject PyUnicode_FromWideChar(Pointer w, long size);
513
514
/**
515
* Create single-character Unicode string
516
* @param ordinal - Unicode code point
517
* @return New Unicode object
518
*/
519
public static native PyObject PyUnicode_FromOrdinal(int ordinal);
520
521
/**
522
* Create Unicode string using format string
523
* @param format - Printf-style format string
524
* @param args - Format arguments
525
* @return New Unicode object
526
*/
527
public static native PyObject PyUnicode_FromFormat(String format, Object... args);
528
```
529
530
### Unicode Access and Manipulation
531
532
```java { .api }
533
/**
534
* Get length of Unicode string
535
* @param unicode - Unicode object
536
* @return Length in code points, or -1 on error
537
*/
538
public static native long PyUnicode_GetLength(PyObject unicode);
539
540
/**
541
* Read character at index
542
* @param unicode - Unicode object
543
* @param index - Character index
544
* @return Unicode code point, or -1 on error
545
*/
546
public static native int PyUnicode_ReadChar(PyObject unicode, long index);
547
548
/**
549
* Write character at index
550
* @param unicode - Unicode object
551
* @param index - Character index
552
* @param character - Unicode code point to write
553
* @return 0 on success, -1 on error
554
*/
555
public static native int PyUnicode_WriteChar(PyObject unicode, long index, int character);
556
557
/**
558
* Extract substring
559
* @param str - Unicode object
560
* @param start - Start index (inclusive)
561
* @param end - End index (exclusive)
562
* @return New Unicode substring
563
*/
564
public static native PyObject PyUnicode_Substring(PyObject str, long start, long end);
565
```
566
567
### Unicode Conversion
568
569
```java { .api }
570
/**
571
* Convert Unicode to UCS4 array
572
* @param unicode - Unicode object
573
* @param buffer - Buffer to write to
574
* @param bufsize - Size of buffer
575
* @return Pointer to UCS4 data, or NULL on error
576
*/
577
public static native IntPointer PyUnicode_AsUCS4(PyObject unicode, IntPointer buffer, long bufsize);
578
579
/**
580
* Convert Unicode to UCS4 array (new copy)
581
* @param unicode - Unicode object
582
* @return New UCS4 array, or NULL on error
583
*/
584
public static native IntPointer PyUnicode_AsUCS4Copy(PyObject unicode);
585
586
/**
587
* Convert Unicode to wide character string
588
* @param unicode - Unicode object
589
* @param w - Wide character buffer
590
* @param size - Size of buffer
591
* @return Number of characters written, or -1 on error
592
*/
593
public static native long PyUnicode_AsWideChar(PyObject unicode, Pointer w, long size);
594
595
/**
596
* Convert Unicode to wide character string (new allocation)
597
* @param unicode - Unicode object
598
* @param size - Pointer to receive size
599
* @return New wide character string, or NULL on error
600
*/
601
public static native Pointer PyUnicode_AsWideCharString(PyObject unicode, SizeTPointer size);
602
```
603
604
### String Interning
605
606
```java { .api }
607
/**
608
* Intern string in place
609
* @param string - Pointer to string object (modified)
610
*/
611
public static native void PyUnicode_InternInPlace(PointerPointer string);
612
613
/**
614
* Create interned string from C string
615
* @param v - C string to intern
616
* @return Interned Unicode object
617
*/
618
public static native PyObject PyUnicode_InternFromString(String v);
619
```
620
621
### Unicode Encoding/Decoding
622
623
```java { .api }
624
/**
625
* Decode encoded object to Unicode
626
* @param obj - Encoded object
627
* @param encoding - Encoding name (or NULL for default)
628
* @param errors - Error handling mode (or NULL for default)
629
* @return New Unicode object
630
*/
631
public static native PyObject PyUnicode_FromEncodedObject(PyObject obj, String encoding, String errors);
632
633
/**
634
* Convert object to Unicode
635
* @param obj - Object to convert
636
* @return New Unicode object
637
*/
638
public static native PyObject PyUnicode_FromObject(PyObject obj);
639
```
640
641
**Usage Example:**
642
643
```java
644
// Create and manipulate Unicode strings
645
PyObject str1 = PyUnicode_FromString("Hello, 世界");
646
PyObject str2 = PyUnicode_FromString("!");
647
648
// Get string length
649
long length = PyUnicode_GetLength(str1); // Returns 9
650
651
// Read individual characters
652
int firstChar = PyUnicode_ReadChar(str1, 0); // 'H'
653
int lastChar = PyUnicode_ReadChar(str1, 8); // '界'
654
655
// Create substring
656
PyObject substr = PyUnicode_Substring(str1, 0, 5); // "Hello"
657
658
// Create formatted string
659
PyObject formatted = PyUnicode_FromFormat("Value: %d", 42);
660
661
// Intern frequently used strings
662
PyObject interned = PyUnicode_InternFromString("__name__");
663
```
664
665
### Numeric Types - Integer Operations
666
667
Essential operations for Python integer objects (PyLong), which handle arbitrary precision integers.
668
669
```java { .api }
670
/**
671
* Create Python integer from long value
672
* @param value - Long value to convert
673
* @return New PyLong object
674
*/
675
public static native PyObject PyLong_FromLong(long value);
676
677
/**
678
* Create Python integer from unsigned long value
679
* @param value - Unsigned long value to convert
680
* @return New PyLong object
681
*/
682
public static native PyObject PyLong_FromUnsignedLong(@Cast("unsigned long") long value);
683
684
/**
685
* Create Python integer from long long value
686
* @param value - Long long value to convert
687
* @return New PyLong object
688
*/
689
public static native PyObject PyLong_FromLongLong(@Cast("long long") long value);
690
691
/**
692
* Create Python integer from string
693
* @param str - String representation of integer
694
* @param base - Number base (2-36, or 0 for auto-detection)
695
* @return New PyLong object, or NULL on error
696
*/
697
public static native PyObject PyLong_FromString(String str, @Cast("char**") PointerPointer pend, int base);
698
699
/**
700
* Convert Python integer to long value
701
* @param obj - PyLong object
702
* @return Long value, or -1 on error
703
*/
704
public static native long PyLong_AsLong(PyObject obj);
705
706
/**
707
* Convert Python integer to long value with overflow detection
708
* @param obj - PyLong object
709
* @param overflow - Pointer to int that will be set to 0, +1, or -1 for no overflow, positive overflow, or negative overflow
710
* @return Long value
711
*/
712
public static native long PyLong_AsLongAndOverflow(PyObject obj, IntPointer overflow);
713
714
/**
715
* Convert Python integer to unsigned long value
716
* @param obj - PyLong object
717
* @return Unsigned long value, or (unsigned long)-1 on error
718
*/
719
public static native @Cast("unsigned long") long PyLong_AsUnsignedLong(PyObject obj);
720
721
/**
722
* Convert Python integer to double value
723
* @param obj - PyLong object
724
* @return Double value, or -1.0 on error
725
*/
726
public static native double PyLong_AsDouble(PyObject obj);
727
```
728
729
### Numeric Types - Float Operations
730
731
Operations for Python floating point objects (PyFloat), which represent double precision numbers.
732
733
```java { .api }
734
/**
735
* Create Python float from double value
736
* @param value - Double value to convert
737
* @return New PyFloat object
738
*/
739
public static native PyObject PyFloat_FromDouble(double value);
740
741
/**
742
* Create Python float from string
743
* @param str - String representation of float
744
* @return New PyFloat object, or NULL on error
745
*/
746
public static native PyObject PyFloat_FromString(PyObject str);
747
748
/**
749
* Convert Python float to double value
750
* @param obj - PyFloat object
751
* @return Double value, or -1.0 on error (use PyErr_Occurred() to check)
752
*/
753
public static native double PyFloat_AsDouble(PyObject obj);
754
755
/**
756
* Get maximum finite float value
757
* @return Maximum representable finite float value
758
*/
759
public static native double PyFloat_GetMax();
760
761
/**
762
* Get minimum positive float value
763
* @return Minimum positive representable float value
764
*/
765
public static native double PyFloat_GetMin();
766
767
/**
768
* Get float precision information
769
* @return PyFloat_Info object with precision details
770
*/
771
public static native PyObject PyFloat_GetInfo();
772
```
773
774
**Usage Examples:**
775
776
```java
777
// Working with integers
778
PyObject pyInt = PyLong_FromLong(42);
779
long value = PyLong_AsLong(pyInt); // 42
780
781
// Large integer conversion
782
PyObject bigInt = PyLong_FromString("123456789012345678901234567890", null, 10);
783
IntPointer overflow = new IntPointer(1);
784
long result = PyLong_AsLongAndOverflow(bigInt, overflow);
785
if (overflow.get() != 0) {
786
// Handle overflow - convert to double instead
787
double bigValue = PyLong_AsDouble(bigInt);
788
}
789
790
// Working with floats
791
PyObject pyFloat = PyFloat_FromDouble(3.14159);
792
double piValue = PyFloat_AsDouble(pyFloat); // 3.14159
793
794
// String to number conversion
795
PyLong_FromString("42", null, 10); // Integer from string
796
PyFloat_FromString(PyUnicode_FromString("3.14")); // Float from string
797
```
798
799
### Tuple Operations
800
801
Essential operations for Python tuple objects (PyTuple), which are immutable sequences.
802
803
```java { .api }
804
/**
805
* Create new tuple with specified size
806
* @param size - Number of elements in tuple
807
* @return New PyTuple object, or NULL on error
808
*/
809
public static native PyObject PyTuple_New(@Cast("Py_ssize_t") long size);
810
811
/**
812
* Get size of tuple
813
* @param tuple - PyTuple object
814
* @return Number of elements, or -1 on error
815
*/
816
public static native @Cast("Py_ssize_t") long PyTuple_Size(PyObject tuple);
817
818
/**
819
* Get item from tuple at specified index
820
* @param tuple - PyTuple object
821
* @param index - Index of item to retrieve
822
* @return Borrowed reference to item, or NULL on error
823
*/
824
public static native PyObject PyTuple_GetItem(PyObject tuple, @Cast("Py_ssize_t") long index);
825
826
/**
827
* Set item in tuple at specified index
828
* @param tuple - PyTuple object (must be newly created)
829
* @param index - Index where to set item
830
* @param item - Item to set (reference will be stolen)
831
* @return 0 on success, -1 on error
832
*/
833
public static native int PyTuple_SetItem(PyObject tuple, @Cast("Py_ssize_t") long index, PyObject item);
834
835
/**
836
* Get slice of tuple
837
* @param tuple - PyTuple object
838
* @param low - Start index (inclusive)
839
* @param high - End index (exclusive)
840
* @return New PyTuple object with slice, or NULL on error
841
*/
842
public static native PyObject PyTuple_GetSlice(PyObject tuple, @Cast("Py_ssize_t") long low, @Cast("Py_ssize_t") long high);
843
844
/**
845
* Pack arguments into tuple
846
* @param format - Format string (like "iii" for 3 integers)
847
* @param ... - Arguments to pack
848
* @return New PyTuple object, or NULL on error
849
*/
850
public static native PyObject Py_BuildValue(String format, Object... args);
851
```
852
853
**Usage Examples:**
854
855
```java
856
// Create and populate tuple
857
PyObject tuple = PyTuple_New(3);
858
PyTuple_SetItem(tuple, 0, PyLong_FromLong(1));
859
PyTuple_SetItem(tuple, 1, PyUnicode_FromString("hello"));
860
PyTuple_SetItem(tuple, 2, PyFloat_FromDouble(3.14));
861
862
// Access tuple elements
863
long size = PyTuple_Size(tuple); // 3
864
PyObject firstItem = PyTuple_GetItem(tuple, 0); // Borrowed reference to 1
865
PyObject secondItem = PyTuple_GetItem(tuple, 1); // Borrowed reference to "hello"
866
867
// Create tuple from slice
868
PyObject slice = PyTuple_GetSlice(tuple, 1, 3); // Contains "hello" and 3.14
869
870
// Build tuple using format string
871
PyObject coordinates = Py_BuildValue("(dd)", 12.5, 34.7); // (12.5, 34.7)
872
PyObject mixed = Py_BuildValue("(isi)", 42, "test", 100); // (42, "test", 100)
873
```
874
875
## Key Object Types
876
877
```java { .api }
878
/**
879
* Base class for all Python objects
880
*/
881
class PyObject extends Pointer { }
882
883
/**
884
* Base class for variable-size objects (lists, tuples, strings)
885
*/
886
class PyVarObject extends PyObject { }
887
888
/**
889
* Python type objects (represent types like int, str, list)
890
*/
891
class PyTypeObject extends PyVarObject { }
892
893
/**
894
* Python list objects
895
*/
896
class PyListObject extends PyVarObject { }
897
898
/**
899
* Python dictionary objects
900
*/
901
class PyDictObject extends PyObject { }
902
903
/**
904
* Python tuple objects
905
*/
906
class PyTupleObject extends PyVarObject { }
907
908
/**
909
* Python set objects
910
*/
911
class PySetObject extends PyObject { }
912
913
/**
914
* Python Unicode string objects
915
*/
916
class PyUnicodeObject extends PyObject { }
917
918
/**
919
* Python bytes objects
920
*/
921
class PyBytesObject extends PyVarObject { }
922
923
/**
924
* Python bytearray objects
925
*/
926
class PyByteArrayObject extends PyVarObject { }
927
928
/**
929
* Python integer objects (arbitrary precision)
930
*/
931
class PyLongObject extends PyVarObject { }
932
933
/**
934
* Python float objects
935
*/
936
class PyFloatObject extends PyObject { }
937
938
/**
939
* Python boolean objects
940
*/
941
class PyBoolObject extends PyLongObject { }
942
943
/**
944
* Python complex number objects
945
*/
946
class PyComplexObject extends PyObject { }
947
```
948
949
## Advanced Usage Patterns
950
951
### Reference Management
952
953
```java
954
// Proper reference management
955
PyObject obj = PyList_New(10); // New reference
956
957
// When adding to containers, reference is stolen or borrowed
958
PyList_SetItem(obj, 0, PyUnicode_FromString("item")); // Steals reference
959
960
// When getting from containers, reference is usually borrowed
961
PyObject item = PyList_GetItem(obj, 0); // Borrowed reference
962
// Use PyList_GetItemRef for new reference if needed
963
964
// For long-term storage, increment reference count
965
Py_INCREF(item); // If this function were available
966
```
967
968
### Type Checking
969
970
```java
971
// Check object types
972
if (Py_IS_TYPE(obj, PyList_Type())) {
973
// Object is a list
974
long size = PyList_Size(obj);
975
}
976
977
// Check identity
978
if (Py_Is(obj1, obj2) != 0) {
979
// Objects are the same object
980
}
981
982
// Get and check type
983
PyTypeObject objType = Py_TYPE(obj);
984
```
985
986
### Safe Object Access
987
988
```java
989
// Always check for errors after operations
990
PyObject result = PyDict_GetItemWithError(dict, key);
991
if (result == null && PyErr_Occurred() != null) {
992
// An error occurred
993
PyErr_Clear();
994
return;
995
}
996
997
// Safe list access
998
long size = PyList_Size(list);
999
if (index >= 0 && index < size) {
1000
PyObject item = PyList_GetItem(list, index);
1001
// Use item
1002
}
1003
```
1004
1005
## Important Notes
1006
1007
### Reference Counting
1008
1009
Most object creation functions return new references that the caller owns. Container modification functions often steal references. Always check the documentation for reference ownership.
1010
1011
### Error Handling
1012
1013
Many functions return NULL or -1 on error. Always check for errors using `PyErr_Occurred()` after API calls.
1014
1015
### Thread Safety
1016
1017
All object operations require the GIL (Global Interpreter Lock) to be held. Use `PyGILState_Ensure()` and `PyGILState_Release()` when calling from multiple threads.
1018
1019
### Memory Management
1020
1021
Python objects are garbage collected. Keep references to objects you need to prevent premature collection.