[Fixed]-Why declare field widget before super init?

1πŸ‘

βœ…

I currently have no way to confirm this, but I would provide a possible way to explain this.

It’s clearer to check the source code for answer here. self.widget is expecting a class and widget will later be initialized as a class instance in __init__ in parent class:

widget = widget or self.widget
if isinstance(widget, type):
    widget = widget()    # the instance initialization

If you do the assignment after super, your widget remains a class and will never be initialized, thus it is not going to work.

On the other hand, error_messages is actually an optional parameter for __init__ method. If you provide that in __init__ function, it will take it to the self.error_messages. Otherwise, it’s empty dict:

messages = {}
for c in reversed(self.__class__.__mro__):
    messages.update(getattr(c, 'default_error_messages', {}))
# see here. Did you provide any error_messages? If no then {}
messages.update(error_messages or {})
# self.error_messages might be {} because the above code
self.error_messages = messages

So if you do self.error_messsages before the super, it will be overridden with {}.

πŸ‘€Shang Wang

Leave a comment