Skip to content

Commit

Permalink
Add pythonization for freezing class attribute and preventing creatin…
Browse files Browse the repository at this point in the history
…g new attrubes by mistake (#663)

* test setting new attributes for objects in python

* add pythonization freezing class for new attribute creation

* fix typo in freeze_class.py

---------

Co-authored-by: hegner <[email protected]>
  • Loading branch information
m-fila and hegner authored Sep 6, 2024
1 parent 8a117ee commit 27e92d5
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
31 changes: 31 additions & 0 deletions python/podio/pythonizations/freeze_class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Prevent creating new attributes for existing objects
The new attributes created in Python won't be visible for podio IO
therefore preventing the addition of new attributes for podio objects
might be desirable and help detecting mis-assignments"""

from .utils.pythonizer import Pythonizer


class FreezeClassPythonizer(Pythonizer):
"""Prevent setting new attributes"""

@classmethod
def priority(cls):
"""This most likely should be the last pythonization loaded
otherwise it may interfere with creating attributes during other pythonizations"""
return 99

@classmethod
def filter(cls, class_, name):
return True

@classmethod
def modify(cls, class_, name):
def freeze_setattr(self, attr, val):
object_type = type(self)
if attr not in object_type.__dict__:
raise AttributeError(f"'{object_type}' object has no attribute '{attr}'")
old_setattr(self, attr, val)

old_setattr = class_.__setattr__
class_.__setattr__ = freeze_setattr
12 changes: 12 additions & 0 deletions python/podio/test_CodeGen.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,15 @@ def test_bound_check(self):
with self.assertRaises(IndexError):
_ = collection[20]
_ = collection[0]


class AttributeCreationTest(unittest.TestCase):
"""Setting new attributes test"""

def test_disable_new_attribute_creation(self):
component = nsp.AnotherNamespaceStruct()
self.assertEqual(component.x, 0)
component.x = 1
self.assertEqual(component.x, 1)
with self.assertRaises(AttributeError):
component.not_existing_attribute = 0
5 changes: 5 additions & 0 deletions tests/datalayout.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ components :
Members:
- ex2::NamespaceStruct data

nsp::AnotherNamespaceStruct:
Members:
- int x
- int y

StructWithFixedWithTypes:
Members:
- uint16_t fixedUnsigned16 // unsigned int with exactly 16 bits
Expand Down

0 comments on commit 27e92d5

Please sign in to comment.