How to resolve bindings during execution with embedded Python?
-
24-10-2019 - |
Question
I'm embedding Python into a C++ application. I plan to use PyEval_EvalCode
to execute Python code, but instead of providing the locals and globals as dictionaries, I'm looking for a way to have my program resolve symbol references dynamically.
For example, let's say my Python code consists of the following expression:
bear + lion * bunny
Instead of placing bear
, lion
and bunny
and their associated objects into the dictionaries that I'm passing to PyEval_EvalCode
, I'd like the Python interpreter to call back my program and request these named objects.
Is there a way to accomplish this?
Solution
By providing the locals and globals dictionaries, you are providing the environment in which the evaled code is executed. That effectively provides you with an interface to map names to objects defined in the C++ app.
Can you clarify why you do not want to use the dictionaries?
Another thing you could do is process the string in C++ and do string substitution before you eval the code....
OTHER TIPS
Possibly. I've never tried this but in theory you might be able to implement a small extension class in C++ that overrides the __getattr__
method (probably via the tp_as_mapping
or tp_getattro
function pointers of PyTypeObject
). Pass an instance of this as locals and/or globals to PyEval_EvalCode
and your C++ method should be asked to resolve your lions, tigers, & bears for you.