Commit c78684b3 authored by Samuel GAIST's avatar Samuel GAIST

[utils] Add frozen class decorator

This decorator disable the possibility to add attributes to
to python objects outside the __init__ function.
parent fcc3c8fd
......@@ -31,10 +31,11 @@ Helper methods and utilities
import os
import sys
import logging
import jinja2
import logging
from functools import wraps
logger = logging.getLogger(__name__)
......@@ -217,3 +218,37 @@ def setup_logger(name, verbosity):
logger.setLevel(logging.DEBUG)
return logger
def frozen(cls):
"""
Don't allow new attributes to be added outside of init
Based on https://stackoverflow.com/a/29368642/5843716
"""
cls.__frozen = False
def frozensetattr(self, key, value):
"""Don't allow attributes to be added outside of __init__"""
if self.__frozen and not hasattr(self, key):
print(
"Class {} is frozen. Cannot set {} = {}".format(
cls.__name__, key, value
)
)
else:
object.__setattr__(self, key, value)
def init_decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
self.__frozen = True
return wrapper
cls.__setattr__ = frozensetattr
cls.__init__ = init_decorator(cls.__init__)
return cls
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment