Can I get the values ​​used to create Python 2.7 xrange from the object itself?

If s is a slice object in Python created using either s = slice(start, stop, step) or (in the appropriate context) start:stop:step , the values ​​used to construct s are accessible from the slice object itself as s.start , s.stop and s.step .

Similar start , stop and step members are available in range objects in Python 3.4 [ Issue9896 ], for example, range(1, 4, 2).start == 1 .

However, Python 2.7 xrange objects do not have start , stop and step members. Is there any other way to get the values ​​used to build xrange from the object itself?

+5
source share
2 answers

You can restore the original start and step arguments, but not always the original stop argument.

One way to get the values ​​is to look at the __reduce__ (or __reduce_ex__ ) method of the xrange object (usually used for etching):

 >>> x = xrange(10) >>> x.__reduce__()[1] (0, 10, 1) >>> y = xrange(2, 100, 13) >>> y.__reduce__()[1] (2, 106, 13) 

Then start, stop, step = y.__reduce__()[1] will assign the three variable names to the corresponding integers. The start and step values ​​are always the original values ​​that were used to build the xrange object.

stop may be higher than the argument originally used to compress the object. For any xrange x object, it is x[-1] + step .

In general, it is not possible to restore the original stop argument after creating the xrange object. If you examine the source for xrange , you will see that this object does not store a reference to a specific stop value, but only the start value, step value and total length of the iterator. When str or __reduce__ , the object will calculate the last possible stop value using the get_stop_for_range internal function.

This contrasts with the Python 3 range object, which remembers the original stop value.

+4
source

This is not very, but you can analyze the str xrange view

 >>> rr = xrange(1, 4, 2) >>> str(rr) 'xrange(1, 5, 2)' >>> start = str(rr).split('(')[1].split(',')[0] >>> start 1 

etc.

Please note that max cannot be reliably found this way if there are steps in this range. For example, in the above example, (1, 4, 2) becomes (1, 5, 2) in the str view.

+3
source

All Articles