Skip to content

Commit e0be5db

Browse files
author
AlexanderMueller
committed
test fix
1 parent d21cee3 commit e0be5db

File tree

2 files changed

+14
-13
lines changed

2 files changed

+14
-13
lines changed

include/pybind11/functional.h

+12-12
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include "pybind11.h"
1515

1616
#include <functional>
17+
#include <iostream>
1718

1819
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
1920
PYBIND11_NAMESPACE_BEGIN(detail)
@@ -129,24 +130,23 @@ struct type_caster<std::function<Return(Args...)>> {
129130
// See PR #1413 for full details
130131
} else {
131132
// Check number of arguments of Python function
132-
auto argCountFromFuncCode = [&](handle &obj) {
133-
// This is faster then doing import inspect and
134-
// inspect.signature(obj).parameters
135-
136-
object argCount = obj.attr("co_argcount");
137-
return argCount.template cast<size_t>();
133+
auto get_argument_count = [](const handle &obj) -> size_t {
134+
// Faster then `import inspect` and `inspect.signature(obj).parameters`
135+
return obj.attr("co_argcount").cast<size_t>();
138136
};
139137
size_t argCount = 0;
140138

141-
handle codeAttr = PyObject_GetAttrString(src.ptr(), "__code__");
139+
handle empty;
140+
object codeAttr = getattr(src, "__code__", empty);
141+
142142
if (codeAttr) {
143-
argCount = argCountFromFuncCode(codeAttr);
143+
argCount = get_argument_count(codeAttr);
144144
} else {
145-
handle callAttr = PyObject_GetAttrString(src.ptr(), "__call__");
145+
object callAttr = getattr(src, "__call__", empty);
146+
146147
if (callAttr) {
147-
handle codeAttr2 = PyObject_GetAttrString(callAttr.ptr(), "__code__");
148-
argCount = argCountFromFuncCode(codeAttr2)
149-
- 1; // we have to remove the self argument
148+
object codeAttr2 = getattr(callAttr, "__code__");
149+
argCount = get_argument_count(codeAttr2) - 1; // removing the self argument
150150
} else {
151151
// No __code__ or __call__ attribute, this is not a proper Python function
152152
return false;

tests/test_callbacks.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,8 @@ def __call__(self, a):
112112
return a
113113

114114
assert m.dummy_function_overloaded_std_func_arg(f) == 9
115-
assert m.dummy_function_overloaded_std_func_arg(A()) == 9
115+
a = A()
116+
assert m.dummy_function_overloaded_std_func_arg(a) == 9
116117
assert m.dummy_function_overloaded_std_func_arg(lambda i: i) == 9
117118

118119
def f2(a, b):

0 commit comments

Comments
 (0)