-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add pythonization for freezing class attribute and preventing creatin…
…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
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters