Search code examples
pythonstringmultiplicationcpython

How is string multiplication implemented in CPython?


Python allows the multiplication of strings by integers:

>>> 'hello' * 5
'hellohellohellohellohello'

How is this implemented in CPython?

I would particularly appreciate a pointer to the source code; the Mercurial repository is a labyrinth beyond my abilities to navigate.


Solution

  • Note: I'm going to answer for Python 3, where the string type is called PyUnicode. Python 2 is similar.

    When a BINARY_MULTIPLY opcode is executed (in Python/ceval.c), there are two possible slots that can get called: PyNumberMethods.nb_multiply and PySequenceMethods.sq_repeat. (This is in PyNumber_Multiply, in Objects/abstract.c):

    PyObject *
    PyNumber_Multiply(PyObject *v, PyObject *w)
    {
        PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
        if (result == Py_NotImplemented) {
            // call sq_repeat on either side if available
    

    PyUnicode implements the latter, in unicode_repeat:

    static PyObject*
    unicode_repeat(PyObject *str, Py_ssize_t len)
    {
        // ...