Skip to content

Question: type annotating a validator callback #1503

@jacopoabramo

Description

@jacopoabramo

I'm trying to correctly type hint the validator callback function of a class declared via @define and I'm a bit confused. Given the following example simplified from the documentation:

from attrs import define

@define
class C:
    x: int
    
    @x.validator
    def fits_byte(self, attribute, value):
        if not 0 <= value < 256:
            raise ValueError("value out of bounds")

What's the correct annotation for fits_byte? At a glance, it looked to me like it should be:

from typing import TYPE_CHECKING
from attrs import define

if TYPE_CHECKING:
    from attrs import Attribute

@define
class C:
    x: int
    
    @x.validator
    def fits_byte(self, attribute: Attribute[int], value: int) -> None:
        ... # rest of the code

Is this correct?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions