Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Set __file__ constant when using eval_file (#1300) #3233

Merged
merged 13 commits into from
Sep 9, 2021
8 changes: 8 additions & 0 deletions include/pybind11/eval.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,14 @@ object eval_file(str fname, object global = globals(), object local = object())
pybind11_fail("File \"" + fname_str + "\" could not be opened!");
}

// Python2 API requires this to be encoded to filesystemencoding.
Copy link
Collaborator

@rwgk rwgk Sep 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks great.
I see the env.PY3 is giving us trouble. There is another easy trick, JIC there isn't a better one:

if str is not bytes:  # Python 2 is not supported.

(We'll find that easily when we clear out Python 2 with the firehose in a few months.)

// Therefore, we don't bother supporting it.
#if PY_VERSION_HEX >= 0x03000000
if (!global.contains("__file__")) {
global["__file__"] = std::move(fname);
}
#endif

#if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION)
PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(),
local.ptr());
Expand Down
5 changes: 5 additions & 0 deletions tests/test_cmake_build/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@

import test_cmake_build

from .. import env

if env.PY3:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the matching guard in C++ we are as much creating a problem as we are solving one.

assert isinstance(__file__, str) # Test this is properly set

assert test_cmake_build.add(1, 2) == 3
print("{} imports, runs, and adds: 1 + 2 = 3".format(sys.argv[1]))