Allow attrs kw_only arguments at any position by markusschmaus · Pull Request #8803 · python/mypy

import inspect
from typing import Optional

import attr


@attr.s()
class Valid:
    kw_only: Optional[str] = attr.ib(default=None, kw_only=True)
    param: int = attr.ib()
    optional: bool = attr.ib(default=False)


valid1 = Valid(1)
print(valid1)
valid2 = Valid(2, kw_only='something')
print(valid2)
invalid2 = Valid(2, 'something')
print(invalid2)
invalid3 = Valid('something')
print(invalid3)


@attr.s()
class Valid2:
    param: int = attr.ib()
    kw_only: Optional[str] = attr.ib(default=None, kw_only=True)


valid3 = Valid2(3)
print(valid3)
valid4 = Valid2(4, kw_only='something')
print(valid4)

try:
    invalid = Valid2(4, 'something')
except TypeError:
    pass
mypy my_example.py
my_example.py:18: error: Argument 2 to "Valid" has incompatible type "str"; expected "bool"
my_example.py:20: error: Argument 1 to "Valid" has incompatible type "str"; expected "int"
my_example.py:36: error: Too many positional arguments for "Valid2"
Found 3 errors in 1 file (checked 1 source file)