How can the built-in range function take a single argument or three?

前端 未结 4 1811
借酒劲吻你
借酒劲吻你 2020-12-06 05:44

I would like to know, if anyone can tell me, how the range function can take either: a single argument, range(stop), or range(start, stop), or

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 05:58

    The beauty of open-source software is that you can just look it up in the source:

    (TL;DR: yes, it uses varargs)

    if (PyTuple_Size(args) <= 1) {
        if (!PyArg_UnpackTuple(args, "range", 1, 1, &stop))
            return NULL;
        stop = PyNumber_Index(stop);
        if (!stop)
            return NULL;
        start = PyLong_FromLong(0);
        if (!start) {
            Py_DECREF(stop);
            return NULL;
        }
        step = PyLong_FromLong(1);
        if (!step) {
            Py_DECREF(stop);
            Py_DECREF(start);
            return NULL;
        }
    }
    else {
        if (!PyArg_UnpackTuple(args, "range", 2, 3,
                               &start, &stop, &step))
            return NULL;
    
        /* Convert borrowed refs to owned refs */
        start = PyNumber_Index(start);
        if (!start)
            return NULL;
        stop = PyNumber_Index(stop);
        if (!stop) {
            Py_DECREF(start);
            return NULL;
        }
        step = validate_step(step);    /* Caution, this can clear exceptions */
        if (!step) {
            Py_DECREF(start);
            Py_DECREF(stop);
            return NULL;
        }
    }
    

提交回复
热议问题