Search code examples
pythonattr

Python attrs validator and __attrs_post_init__() are not called


I created a class using @attr.s and defined an attribute validator and attrs_post_init() method. I expect these methods to be automatically called when instantiating an object of this class. But these do not seem to be called at all anytime before or after init().

import attr
from typeguard import typechecked
from typing import Any, Optional

@attr.s(auto_attribs=True, init=False)
class Entry:
    name: Optional[str] = attr.ib()

    @typechecked
    def __init__(
        self, name: Optional[str] = None
    ):
        print("Entered init")
        self.name = name

    @name.validator
    def name_validator(self, _attribute: Any, value: Optional[str]) -> None:
        print("Entered validator")

    def __attrs_post_init__(self) -> None:
        print("Entered post")
        
Entry("Bob")

This only prints Entered init.

When do the attribute validator and attrs_post_init() method get called?


Solution

  • attrs cannot perform work at object construction time unless you let it handle object construction. The things you are expecting to happen would normally happen in the generated __init__ method, but you turned that off.

    By rejecting the generated __init__ and implementing your own, you have taken responsibility for these tasks. If you want validation, you need to do it. If you want __attrs_post_init__ to be called, you need to call it.