Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've been trying to solve very similar problem.</p> <p>The conclusion I've come to suggests there is no way to determine name of current function or caller(s) at the level of Python C API. The reason being, Python interpreter puts on call stack only pure Python functions (implemented in Python itself). Functions implemented in C, regardless if registered in module methods table, are not put on Python stack, thus it's not possible to find them inspecting the stack frames.</p> <p>Here is a quick example in Python illustrating what I wanted to achieve (I assume Juan asks for similar behaviour):</p> <pre><code>import sys def foo(): print('foo:', sys._getframe(0).f_code.co_name) def bar(): print('bar:', sys._getframe(0).f_code.co_name) foo() bar() </code></pre> <p>Here is close equivalent of this example (based on the <a href="http://docs.python.org/release/3.2.1/extending/embedding.html#extending-embedded-python" rel="nofollow">Python 3 docs</a>) but implemented using Python C API:</p> <pre><code>// Based on example from Python 3.2.1 documentation, 5.4. Extending Embedded Python // http://docs.python.org/release/3.2.1/extending/embedding.html#extending-embedded-python // #include &lt;Python.h&gt; #include &lt;frameobject.h&gt; static void foo() { PyThreadState * ts = PyThreadState_Get(); PyFrameObject* frame = ts-&gt;frame; while (frame != 0) { char const* filename = _PyUnicode_AsString(frame-&gt;f_code-&gt;co_filename); char const* name = _PyUnicode_AsString(frame-&gt;f_code-&gt;co_name); printf("foo: filename=%s, name=%s\n", filename, name); frame = frame-&gt;f_back; } } static void bar() { PyRun_SimpleString( "import sys\n" "print(\"bar: filename=%s, name=%s\" % (sys._getframe(0).f_code.co_filename, sys._getframe(0).f_code.co_name))" ); } static PyObject* emb_numargs(PyObject *self, PyObject *args) { foo(); bar(); PyRun_SimpleString( "import sys\n" "print(\"emb_numargs: filename=%s, name=%s\" % (sys._getframe(0).f_code.co_filename, sys._getframe(0).f_code.co_name))" ); return PyLong_FromLong(0); } static PyMethodDef EmbMethods[] = { {"numargs", emb_numargs, METH_VARARGS, "Return number 0"}, {NULL, NULL, 0, NULL} }; static PyModuleDef EmbModule = { PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods, NULL, NULL, NULL, NULL }; static PyObject* PyInit_emb(void) { return PyModule_Create(&amp;EmbModule); } int main(int argc, char* argv[]) { PyImport_AppendInittab("emb", &amp;PyInit_emb); Py_Initialize(); PyRun_SimpleString( "import emb\n" "print('This is Zero: ', emb.numargs())\n" ); Py_Finalize(); return 0; } </code></pre> <p>I hope this completes Ned's answer too.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload