Search code examples
pythonpython-itertools

What is the current value of a Python itertools counter


The itertools.count counter in Python (2.7.9) is very handy for thread-safe counting. How can I get the current value of the counter though?

The counter increments and returns the last value every time you call next():

import itertools
x = itertools.count()
print x.next()  # 0
print x.next()  # 1
print x.next()  # 2

So far, so good.

I can't find a way to get the current value of the counter without calling next(), which would have the undesirable side-effect of increasing the counter, or using the repr() function.

Following on from the above:

print repr(x)  # "count(3)"

So you could parse the output of repr(). Something like

current_value = int(repr(x)[6:-1])

would do the trick, but is really ugly.

Is there a way to get the current value of the counter more directly?


Solution

  • 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.