Skip to content

Commit 89c281e

Browse files
committed
Make py::isinstance<py::str> less permissive (#1463)
1 parent 1e757b0 commit 89c281e

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

include/pybind11/pytypes.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,6 +943,9 @@ class str : public object {
943943
};
944944
/// @} pytypes
945945

946+
// str::check_ is too permissive for `isinstance` (in particular it allows a `bytes` object)
947+
template <> inline bool isinstance<str>(handle obj) { return PyUnicode_Check(obj.ptr()); }
948+
946949
inline namespace literals {
947950
/** \rst
948951
String literal version of `str`

tests/test_pytypes.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,9 @@ TEST_SUBMODULE(pytypes, m) {
290290
return l;
291291
});
292292

293+
// test_str_isinstance
294+
m.def("is_str_instance", [](py::object o) { return py::isinstance<py::str>(o); });
295+
293296
m.def("test_list_slicing", [](py::list a) {
294297
return a[py::slice(0, -1, 2)];
295298
});

tests/test_pytypes.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,3 +251,8 @@ def test_number_protocol():
251251
def test_list_slicing():
252252
li = list(range(100))
253253
assert li[::2] == m.test_list_slicing(li)
254+
255+
256+
def test_str_isinstance():
257+
assert m.is_str_instance(u"abc")
258+
assert not m.is_str_instance(b"abc")

0 commit comments

Comments
 (0)