PyEval_GetLocals and unreferenced variables

Kasper Peeters kasper at phi-sci.com
Wed Nov 26 05:22:57 EST 2014


I have a question about PyEval_GetLocals(). The normal behaviour of
PyEval_GetLocals(), and in fact of the locals() function in Python
itself, is to return a list which includes only those variables which
are actually referenced in the local scope. Example:

  def fun():
     q=3
     def fun2():
        print(locals())
     fun2()

  fun()

will print "{}" because "q" has not been referenced in fun2(). On the
other hand, if you do

  def fun():
     q=3
     def fun2():
	print(q)
        print(locals())
     fun2()

  fun()

you will instead get "{'q': 3}" as output. All fine and understood.

My question: I want to call a C function inside fun2(), which I want to
give access to the 'q' variable in the fun() scope, _without_ there
being any reference to 'q' in the python code itself. That is, I want
to do:

  def fun():
     q=3
     def fun2():
	cfun()
     fun2()

  fun()

and access 'q' inside the C-function cfun(). If I simply let it call
PyEval_GetLocals, then the result will again not contain "q". Is there
any way in which I can convince python to pull 'q' into the local scope
from within my C code?

Thanks!

Cheers,
Kasper



More information about the Python-list mailing list