L
L
LakeForest2022-01-17 14:02:30
OpenVZ
LakeForest, 2022-01-17 14:02:30

How to write a class decorator to check that a class field has been initialized?

_MODEL = get_model("/service/model")

def check_init_model(func):
    @wraps(func)
    def wrapper(*args, **kw):
        assert args[0] is not None, "Модель не инициализирована"

@check_init_model
class TestClass:
    model = _MODEL 
    def __init__(self, ...):
          ...


TypeError: NoneType takes no arguments

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Panarin, 2015-11-04
@ramjke

https://events.yandex.ru/lib/talks/525/habrahabr.ru/company/centosadmin/blog/212985
_

V
Vindicar, 2022-01-17
@Vindicar

Well, firstly, what does "the variable was initialized" mean? Is the value assigned to a class field valid? So it should be checked by the class itself.
Secondly, the decorator works when the class is declared, not when it is instantiated. So you have to try to wrap the __init__() method in the class you are decorating, if there is one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question