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

On demand create message meta class for upb python #1527

Merged
merged 1 commit into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion python/descriptor.c
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,25 @@ PyObject* PyUpb_Descriptor_Get(const upb_MessageDef* m) {

PyObject* PyUpb_Descriptor_GetClass(const upb_MessageDef* m) {
PyObject* ret = PyUpb_ObjCache_Get(upb_MessageDef_MiniTable(m));
if (ret) return ret;

// On demand create the clss if not exist. However, if users repeatedly
// create and destroy a class, it could trigger a loop. This is not an
// issue now, but if we see CPU waste for repeatedly create and destroy
// in the future, we could make PyUpb_Descriptor_Get() append the descriptor
// to an internal list in DescriptorPool, let the pool keep descriptors alive.
PyObject* py_descriptor = PyUpb_Descriptor_Get(m);
if (py_descriptor == NULL) return NULL;
const char* name = upb_MessageDef_Name(m);
PyObject* dict = PyDict_New();
if (dict == NULL) goto err;
int status = PyDict_SetItemString(dict, "DESCRIPTOR", py_descriptor);
if (status < 0) goto err;
ret = PyUpb_MessageMeta_DoCreateClass(py_descriptor, name, dict);

err:
Py_XDECREF(py_descriptor);
Py_XDECREF(dict);
return ret;
}

Expand Down Expand Up @@ -477,7 +496,7 @@ static PyObject* PyUpb_Descriptor_GetFullName(PyObject* self, void* closure) {
static PyObject* PyUpb_Descriptor_GetConcreteClass(PyObject* self,
void* closure) {
const upb_MessageDef* msgdef = PyUpb_Descriptor_GetDef(self);
return PyUpb_Descriptor_GetClass(msgdef);
return PyUpb_ObjCache_Get(upb_MessageDef_MiniTable(msgdef));
}

static PyObject* PyUpb_Descriptor_GetFile(PyObject* self, void* closure) {
Expand Down
4 changes: 4 additions & 0 deletions python/message.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ PyObject* PyUpb_Message_GetFieldValue(PyObject* _self,
int PyUpb_Message_SetFieldValue(PyObject* _self, const upb_FieldDef* field,
PyObject* value, PyObject* exc);

// Creates message meta class.
PyObject* PyUpb_MessageMeta_DoCreateClass(PyObject* py_descriptor,
const char* name, PyObject* dict);

// Returns the version associated with this message. The version will be
// incremented when the message changes.
int PyUpb_Message_GetVersion(PyObject* _self);
Expand Down
Loading