Skip to content

Commit

Permalink
Support factory= in attr plugin.
Browse files Browse the repository at this point in the history
It works pretty much like default=
  • Loading branch information
euresti committed Mar 22, 2018
1 parent 3a2aa99 commit ee19aed
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
6 changes: 6 additions & 0 deletions mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,12 @@ def _attribute_from_attrib_maker(ctx: 'mypy.plugin.ClassDefContext',
init = _get_bool_argument(ctx, rvalue, 'init', True)
# TODO: Check for attr.NOTHING
attr_has_default = bool(_get_argument(rvalue, 'default'))
attr_has_factory = bool(_get_argument(rvalue, 'factory'))

if attr_has_default and attr_has_factory:
ctx.api.fail("Can't pass both `default` and `factory`.", rvalue)
elif attr_has_factory:
attr_has_default = attr_has_factory

# If the type isn't set through annotation but is passed through `type=` use that.
type_arg = _get_argument(rvalue, 'type')
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-attr.test
Original file line number Diff line number Diff line change
Expand Up @@ -771,3 +771,15 @@ class FFrozen(F):
def bar(self) -> bool:
return self._cb(5, 6)
[builtins fixtures/callable.pyi]

[case testAttrsWithFactory]
from typing import List
import attr
def my_factory() -> int:
return 7
@attr.s
class A:
x: List[int] = attr.ib(factory=list)
y: int = attr.ib(factory=my_factory)
A()
[builtins fixtures/list.pyi]
8 changes: 6 additions & 2 deletions test-data/unit/lib-stub/attr.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ def attr(default: Optional[_T] = ...,
convert: Optional[Callable[[Any], _T]] = ...,
metadata: Any = ...,
type: Optional[Type[_T]] = ...,
converter: Optional[Callable[[Any], _T]] = ...) -> _T: ...
converter: Optional[Callable[[Any], _T]] = ...,
factory: Optional[Callable[[], _T]] = ...,
) -> _T: ...
@overload
def attr(default: None = ...,
validator: None = ...,
Expand All @@ -24,7 +26,9 @@ def attr(default: None = ...,
convert: Optional[Callable[[Any], _T]] = ...,
metadata: Any = ...,
type: None = ...,
converter: None = ...) -> Any: ...
converter: None = ...,
factory: Optional[Callable[[], _T]] = ...,
) -> Any: ...

@overload
def attributes(maybe_cls: _C,
Expand Down

0 comments on commit ee19aed

Please sign in to comment.