What is the current value of a Python itertools counter
Another hack to get next value without advancing iterator is to abuse copy protocol:
>>> c = itertools.count()
>>> c.__reduce__()[1][0]
0
>>> next(c)
0
>>> c.__reduce__()[1][0]
1
Or just take it from object copy:
>>> from copy import copy
>>> next(copy(c))
1
Use the source, Luke!
According to module implementation, it's not possible.
typedef struct {
PyObject_HEAD
Py_ssize_t cnt;
PyObject *long_cnt;
PyObject *long_step;
} countobject;
Current state is stored in cnt
and long_cnt
members, and neither of them is exposed in object API. Only place where it may be retrieved is object __repr__
, as you suggested.
Note that while parsing string you have to consider a non-singular increment case. repr(itertools.count(123, 4))
is equal to 'count(123, 4)'
- logic suggested by you in question would fail in that case.
According to the documentation there is no way to access the current value of the function. itertools.count()
is a generator method from the itertools
module. As such, it is common practice to just simply assign the value of a generator's current value to a variable.
Simply store the the result of the next call:
current_value = x.next()
or ( Built-in python method for Python version ≥ 2.6 )
current_value = next(x)
You could make a wrapper function, or a utility decorator class if you would like some added syntactic sugar, but assignment is standard.