Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add pythonization for freezing class attribute and preventing creating new attrubes by mistake #663

Merged
merged 3 commits into from
Sep 6, 2024
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
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