diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py index b0f1ae784f..a6223c2a7e 100755 --- a/python/google/protobuf/internal/message_test.py +++ b/python/google/protobuf/internal/message_test.py @@ -1340,6 +1340,17 @@ class Proto2Test(unittest.TestCase): self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) + def testDel(self): + msg = unittest_pb2.TestAllTypes() + + # Fields cannot be deleted. + with self.assertRaises(AttributeError): + del msg.optional_int32 + with self.assertRaises(AttributeError): + del msg.optional_bool + with self.assertRaises(AttributeError): + del msg.repeated_nested_message + def testAssignInvalidEnum(self): """Assigning an invalid enum number is not allowed in proto2.""" m = unittest_pb2.TestAllTypes() diff --git a/python/message.c b/python/message.c index 2aea2c5a9f..2cca1c1f0f 100644 --- a/python/message.c +++ b/python/message.c @@ -1005,6 +1005,12 @@ __attribute__((flatten)) static PyObject* PyUpb_Message_GetAttr( static int PyUpb_Message_SetAttr(PyObject* _self, PyObject* attr, PyObject* value) { PyUpb_Message* self = (void*)_self; + + if (value == NULL) { + PyErr_SetString(PyExc_AttributeError, "Cannot delete field attribute"); + return -1; + } + const upb_FieldDef* field; if (!PyUpb_Message_LookupName(self, attr, &field, NULL, PyExc_AttributeError)) {