Commit 4c6bee35 by Aaron Gokaslan Committed by GitHub

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

* Set __file__ constant when using eval_file

* Use const ref

* Use a move instead

* Revert

* Improve test

* Guard test with Python version

* Fix tests

* Dont support Python2 API

* Drop Python2 eval __file__ support

* Hack

* Semisupport Python2

* Take2

* Remove Python2 support
parent 6abf2baa
...@@ -136,6 +136,15 @@ object eval_file(str fname, object global = globals(), object local = object()) ...@@ -136,6 +136,15 @@ object eval_file(str fname, object global = globals(), object local = object())
pybind11_fail("File \"" + fname_str + "\" could not be opened!"); pybind11_fail("File \"" + fname_str + "\" could not be opened!");
} }
// In Python2, this should be encoded by getfilesystemencoding.
// We don't boher setting it since Python2 is past EOL anyway.
// See PR#3233
#if PY_VERSION_HEX >= 0x03000000
if (!global.contains("__file__")) {
global["__file__"] = std::move(fname);
}
#endif
#if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION) #if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION)
PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(),
local.ptr()); local.ptr());
......
...@@ -3,5 +3,8 @@ import sys ...@@ -3,5 +3,8 @@ import sys
import test_cmake_build import test_cmake_build
if str is not bytes: # If not Python2
assert isinstance(__file__, str) # Test this is properly set
assert test_cmake_build.add(1, 2) == 3 assert test_cmake_build.add(1, 2) == 3
print("{} imports, runs, and adds: 1 + 2 = 3".format(sys.argv[1])) print("{} imports, runs, and adds: 1 + 2 = 3".format(sys.argv[1]))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment