Commit c78684b3 authored by Samuel GAIST's avatar Samuel GAIST
Browse files

[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):
return logger
def frozen(cls):
Don't allow new attributes to be added outside of init
Based on
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):
"Class {} is frozen. Cannot set {} = {}".format(
cls.__name__, key, value
object.__setattr__(self, key, value)
def init_decorator(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
Supports Markdown
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