C API for str methods?

Bjorn Pettersen BPettersen at NAREX.com
Fri Aug 2 02:43:00 CEST 2002

Is there a reason why methods like str.split, str.join are not
accessible through a C API? (PyUnicode seems to have a lot more of the
functionality available through a C API although not all of them...)

I'm embedding Python and now I need to do something close to the
following in C++, and I thought I'd be able to take a shortcut through
the Python API:

    # change last expression, e, to "magicVar = e"
    lines = block.split('\n');
    lastLine = lines[-1];

    stmts = '\n'.join(lines[:-1])

    if ';' in lastLine:
        lastLineParts = lastLine.split(';');
        stmts += ';'.join(lastLineParts[:-1])
        stmts += 'magicVar = ' + lastLineParts[-1]
        stmts += 'magicVar = ' + lastLine

    #PyRun_String(stmts, Py_file_input, ...);
    #return PyRun_String("magicVar", Py_eval_input, ...);

In case you are wondering, we want to have a Python codeblock stored in
a database. We currently have two functions to interface to Python
py::stmts() to run top-level statements, unfortunately Python doesn't
return result values for most types when running these through
PyRun_String with Py_file_input, so we also have py::expr() to evaluate
an expression. That combination leads to (very simplified) code like:

  py::stmts("a = nrx.NDate(1970,1,1)")
  int val = py::expr("a.getYear()");

and what we would like is something like:

  int val = py::block(
     "a = nrx.NDate(1970,1,1)\n"

If anyone has solved this problem before and has a better solution I'm
all ears <wink>.

-- bjorn

More information about the Python-list mailing list