pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

global variables not accessible when running scripts from embedded interpreter

Open dbacchet opened this issue 8 years ago • 8 comments

Hello, I have a simple exe that embeds the python interpreter, exposes a local variable and runs a script. The code is the following:

int main(int argc, char *argv[]) {

    py::scoped_interpreter guard{};
    auto locals = py::dict("name"_a="my_name");
    // create a local reference
    py::exec(R"(
s = locals()["name"]
print s
    )", py::globals(), locals);    
    // evaluate a script 
    if (argc > 1) {
        py::eval_file(argv[1], py::globals(), locals);
    }

    return 0;
}

if I run the following script:

global_dict = { "key1" : "new_name1", "key2" : "new_name2" }

print("value of s: {}".format(s))
s = global_dict["key1"]
print("value of s: {}".format(s))

everything runs as expected, but it doesn't work if instead I run the following script, that is functionally equivalent but access the global_dict from a function:

global_dict = { "key1" : 11, "key2" : 12 }

def my_func(s):
    s = global_dict["key1"]

print("value of s: {}".format(s))
my_func(s)
print("value of s: {}".format(s))

the euro that I get is the following:

libc++abi.dylib: terminating with uncaught exception of type pybind11::error_already_set: NameError: global name 'global_dict' is not defined

At:
  script1.py(5): my_func
  script1.py(8): <module>

[1]    33087 abort      ./test script1.py

If I call py::eval_file without the locals parameter (and of course without using the local var defined in the c++ code) I don't see the same problem, and functions can access global variables.

Am I missing something when making the call?

Attached an archive that reproduces the problem with the latest master of pybind11 (431fc0e): pybind11_testcase_globalname.zip If you build and run with ./test script1.py you'll see the problem (only tested on MacOS, using system python 2.7).

Thanks for your support and for this library!

dbacchet avatar Feb 25 '18 06:02 dbacchet

Hey, I ran into the exact same problem. My conclusion was that there is something strange with how python loads variables. Basically CPython compiles and runs your code as a module (because apparently that's the only way python can execute multiple statements). When compiling code as a module Python expects (from my observations) that on the module level globals() is locals(). As a result the lookup of global_dict in your case is done in the py::globals() which does not contain global_dict because when you set it, it gets added to the locals dictionary.

The workaround I found is to use the same dictionary for globals and locals in py::exec. You have to 'copy' stuff defined on a global level manually and don't forget to copy __builtins__ because otherwise python will be confused.

yeganer avatar Feb 28 '18 16:02 yeganer

thanks for the hint! Does this mean that this is not a problem in pybind11, but CPython itself?

dbacchet avatar Mar 01 '18 04:03 dbacchet

@dbacchet This is an implementation detail of CPython itself (see exec documentation). The TLDR is that if exec (in python, through CAPI or with pybind) is called with a locals and globals dictionary, the code is executed as if it was inside a class definition.

yeganer avatar Mar 01 '18 12:03 yeganer

@yeganer, that link explains the behavior I've been seeing very well, thanks! I will try to work around the CPython limitation playing with the globals/locals as you suggested. thanks again!

dbacchet avatar Mar 01 '18 16:03 dbacchet

(Un)fortunately, this turned out to be unrelated to pybind11. Closing.

bstaletic avatar Jul 27 '20 08:07 bstaletic

The workaround I found is to use the same dictionary for globals and locals in py::exec. You have to 'copy' stuff defined on a global level manually and don't forget to copy __builtins__ because otherwise python will be confused.

I'm using pybind to execute custom scripts which interface with C++ code and this solved my last remaining issue. If you run a script which defines a function, when you call that function it won't be able to access anything the script imported/defined at global scope! But passing the module both as globals and locals fixes it completely. How is this not in the FAQ or anywhere in the documentation? I'm stunned nobody else comes across this issue.

caustik avatar Jan 22 '21 22:01 caustik

Dear pybind11 developers, a few weeks ago I started to implement pybind11 library in my C++ application to make it python-scriptable. After a successful implementation I immediately came across this problem and been stacked with it for several days without any solution. Therefore I am also very surprised as @caustik : why this problem is nowhere documented? Anyway, thank you very much for the great library!! Bests, Susnicek

susnicek avatar Mar 02 '21 08:03 susnicek

why this problem is nowhere documented?

Because it's stated that it's just related to Python's exec, and not to pybind11.

YannickJadoul avatar Mar 18 '21 12:03 YannickJadoul