Loading...
Searching...
No Matches
pyFunction.h
1//
2// Copyright 2016 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_TF_PY_FUNCTION_H
8#define PXR_BASE_TF_PY_FUNCTION_H
9
10#include "pxr/pxr.h"
11
12#include "pxr/base/tf/pyCall.h"
13#include "pxr/base/tf/pyLock.h"
14#include "pxr/base/tf/pyObjWrapper.h"
15#include "pxr/base/tf/pyUtils.h"
16
17#include "pxr/external/boost/python/converter/from_python.hpp"
18#include "pxr/external/boost/python/converter/registered.hpp"
19#include "pxr/external/boost/python/converter/rvalue_from_python_data.hpp"
20#include "pxr/external/boost/python/extract.hpp"
21#include "pxr/external/boost/python/handle.hpp"
22#include "pxr/external/boost/python/object.hpp"
23
24#include <functional>
25
26PXR_NAMESPACE_OPEN_SCOPE
27
28template <typename T>
29struct TfPyFunctionFromPython;
30
31template <typename Ret, typename... Args>
32struct TfPyFunctionFromPython<Ret (Args...)>
33{
34 struct Call
35 {
36 TfPyObjWrapper callable;
37
38 Ret operator()(Args... args) {
39 TfPyLock lock;
40 return TfPyCall<Ret>(callable)(args...);
41 }
42 };
43
44 struct CallWeak
45 {
46 TfPyObjWrapper weak;
47
48 Ret operator()(Args... args) {
49 using namespace pxr_boost::python;
50 // Attempt to get the referenced callable object.
51 TfPyLock lock;
52 PyObject *callablePtr;
53 if (Tf_PyWeakrefGetRef(weak.ptr(), &callablePtr) != 1) {
54 TF_WARN("Tried to call an expired python callback");
55 return Ret();
56 }
57 object callable { handle<> { callablePtr } };
58 return TfPyCall<Ret>(callable)(args...);
59 }
60 };
61
62 struct CallMethod
63 {
64 TfPyObjWrapper func;
65 TfPyObjWrapper weakSelf;
66
67 Ret operator()(Args... args) {
68 using namespace pxr_boost::python;
69 // Attempt to get the referenced self parameter, then build a new
70 // instance method and call it.
71 TfPyLock lock;
72 PyObject *selfPtr;
73 if (Tf_PyWeakrefGetRef(weakSelf.ptr(), &selfPtr) != 1) {
74 TF_WARN("Tried to call a method on an expired python instance");
75 return Ret();
76 }
77 object self { handle<> { selfPtr } };
78 object method { handle<> { PyMethod_New(func.ptr(), self.ptr()) } };
79 return TfPyCall<Ret>(method)(args...);
80 }
81 };
82
83 TfPyFunctionFromPython() {
84 RegisterFunctionType<std::function<Ret (Args...)>>();
85 }
86
87 template <typename FuncType>
88 static void
89 RegisterFunctionType() {
90 using namespace pxr_boost::python;
91 converter::registry::
92 insert(&convertible, &construct<FuncType>, type_id<FuncType>());
93 }
94
95 static void *convertible(PyObject *obj) {
96 return ((obj == Py_None) || PyCallable_Check(obj)) ? obj : 0;
97 }
98
99 template <typename FuncType>
100 static void construct(PyObject *src, pxr_boost::python::converter::
101 rvalue_from_python_stage1_data *data) {
102 using std::string;
103 using namespace pxr_boost::python;
104
105 void *storage = ((converter::rvalue_from_python_storage<FuncType> *)
106 data)->storage.bytes;
107
108 if (src == Py_None) {
109 new (storage) FuncType();
110 } else {
111
112 // In the case of instance methods, holding a strong reference will
113 // keep the bound 'self' argument alive indefinitely, which is
114 // undesirable. Unfortunately, we can't just keep a weak reference to
115 // the instance method, because python synthesizes these on-the-fly.
116 // Instead we do something like what PyQt's SIP does, and break the
117 // method into three parts: the class, the function, and the self
118 // parameter. We keep strong references to the class and the
119 // function, but a weak reference to 'self'. Then at call-time, if
120 // self has not expired, we build a new instancemethod and call it.
121 //
122 // Otherwise if the callable is a lambda (checked in a hacky way, but
123 // mirroring SIP), we take a strong reference.
124 //
125 // For all other callables, we attempt to take weak references to
126 // them. If that fails, we take a strong reference.
127 //
128 // This is all sort of contrived, but seems to have the right behavior
129 // for most usage patterns.
130
131 object callable(handle<>(borrowed(src)));
132 PyObject *pyCallable = callable.ptr();
133 PyObject *self =
134 PyMethod_Check(pyCallable) ?
135 PyMethod_GET_SELF(pyCallable) : NULL;
136
137 if (self) {
138 // Deconstruct the method and attempt to get a weak reference to
139 // the self instance.
140 object func(handle<>(borrowed(PyMethod_GET_FUNCTION(
141 pyCallable))));
142 object weakSelf(handle<>(PyWeakref_NewRef(self, NULL)));
143 new (storage)
144 FuncType(CallMethod{
145 TfPyObjWrapper(func),
146 TfPyObjWrapper(weakSelf)
147 });
148
149 } else if (PyObject_HasAttrString(pyCallable, "__name__") &&
150 extract<string>(callable.attr("__name__"))()
151 == "<lambda>") {
152 // Explicitly hold on to strong references to lambdas.
153 new (storage) FuncType(Call{TfPyObjWrapper(callable)});
154 } else {
155 // Attempt to get a weak reference to the callable.
156 if (PyObject *weakCallable =
157 PyWeakref_NewRef(pyCallable, NULL)) {
158 new (storage)
159 FuncType(
160 CallWeak{TfPyObjWrapper(
161 object(handle<>(weakCallable)))});
162 } else {
163 // Fall back to taking a strong reference.
164 PyErr_Clear();
165 new (storage) FuncType(Call{TfPyObjWrapper(callable)});
166 }
167 }
168 }
169
170 data->convertible = storage;
171 }
172};
173
174PXR_NAMESPACE_CLOSE_SCOPE
175
176#endif // PXR_BASE_TF_PY_FUNCTION_H
Miscellaneous Utilities for dealing with script.
Convenience class for accessing the Python Global Interpreter Lock.
Definition pyLock.h:105
Boost Python object wrapper.
TF_API PyObject * ptr() const
Underlying PyObject* access.
#define TF_WARN(...)
Issue a warning, but continue execution.
Definition diagnostic.h:133
Utilities for calling python callables.
Provide a way to call a Python callable.
Definition pyCall.h:40