Access to xrange internal structure

I am trying to use ctypes to extract data from python internal structures. Namely, I'm trying to read 4 fields in xrange:

typedef struct { PyObject_HEAD long start; long step; long len; } rangeobject; 

Is there any standard way to get in such fields inside python itself?

+4
source share
2 answers

You can access data without ctypes :

 >>> obj = xrange(1,11,2) >>> obj.__reduce__()[1] (1, 11, 2) >>> len(obj) 5 

Note that the __reduce__() method is intended for serialization. Read more in this chapter in the documentation .

Refresh . But you can also access internal data with ctypes :

 from ctypes import * PyObject_HEAD = [ ('ob_refcnt', c_size_t), ('ob_type', c_void_p), ] class XRangeType(Structure): _fields_ = PyObject_HEAD + [ ('start', c_long), ('step', c_long), ('len', c_long), ] range_obj = xrange(1, 11, 2) c_range_obj = cast(c_void_p(id(range_obj)), POINTER(XRangeType)).contents print c_range_obj.start, c_range_obj.step, c_range_obj.len 
+5
source

The ctypes module is not intended to access internal Python components. ctypes allows you to handle C libraries in terms of C, but coding in Python.

You probably want a C extension, which in many ways is the opposite of ctypes. With the C extension, you are dealing with Python code in terms of Python, but the code is in C.

UPDATED: since you need pure Python, why do you need to access the internal components of the xrange inline object? xrange is very simple: create your own in Python and do what you want with it.

0
source

All Articles