Skip to content

attrs

ty has built-in support for attrs.

Field declarations and constructors

ty infers the signature of an attrs class's generated __init__ method from the class's fields. In the following example, ty understands the following things:

  1. The class is @frozen, so reassigning server.port leads to an error
  2. The _host field is private; its constructor parameter is therefore named host, without the leading underscore
  3. The port parameter has a default value and is keyword-only.
from attrs import field, frozen


@frozen
class Server:
    _host: str
    port: int = field(default=443, kw_only=True)


server = Server(host="example.com")  # N.B. `host=` rather than `_host=`
server.port = 8443  # error: class is frozen

Server("example.com", port=8443)

Server("example.com", 8443)  # error: port is keyword-only

Default values

Default values can also be specified using @<field>.default decorators. The default value for the port field above could therefore also be specified like this:

@frozen
class Server:
    _host: str
    port: int = field(kw_only=True)

    @port.default
    def _default_port(self) -> int:
        # [some logic to determine the default port]
        return 443


Server("example.com")  # okay: `port` has a default value

Validators

You can pass a validator to field(validator=...) or decorate a method with @<field>.validator. ty does not do anything special here except check the type of the field's value.

@frozen
class Server:
    _host: str
    port: int = field(default=443, kw_only=True)

    @port.validator
    def _check_port(self, attribute: object, value: int) -> None:
        if not 1 <= value <= 65535:
            raise ValueError("port must be between 1 and 65535")


Server("example.com", port=8443)
Server("example.com", port="8443")  # error: port must be an int
Server("example.com", port=70000)  # passes type checking, raises ValueError at runtime

Converters

When a field uses a converter using field(converter=...), or a @<field>.converter decorator, ty uses the converter's input type for the type accepted by the constructor parameter. The field's annotation is used for the type inferred when reading the attribute from an instance of the class:

def parse_port(value: str | int) -> int:
    return int(value)


@frozen
class Server:
    _host: str
    port: int = field(default=443, kw_only=True, converter=parse_port)


# okay: `parse_port` converts the string to an int
server = Server("example.com", port="8443")
reveal_type(server.port)  # revealed: int

Known limitations

ty does not support fields without type annotations. If you still use old-style @attr.s classes, prefer name: str = attr.ib() over name = attr.ib(type=str).