/ lib / attr / __init__.pyi
__init__.pyi
  1  import sys
  2  
  3  from typing import (
  4      Any,
  5      Callable,
  6      Dict,
  7      Generic,
  8      List,
  9      Mapping,
 10      Optional,
 11      Sequence,
 12      Tuple,
 13      Type,
 14      TypeVar,
 15      Union,
 16      overload,
 17  )
 18  
 19  # `import X as X` is required to make these public
 20  from . import converters as converters
 21  from . import exceptions as exceptions
 22  from . import filters as filters
 23  from . import setters as setters
 24  from . import validators as validators
 25  from ._version_info import VersionInfo
 26  
 27  __version__: str
 28  __version_info__: VersionInfo
 29  __title__: str
 30  __description__: str
 31  __url__: str
 32  __uri__: str
 33  __author__: str
 34  __email__: str
 35  __license__: str
 36  __copyright__: str
 37  
 38  _T = TypeVar("_T")
 39  _C = TypeVar("_C", bound=type)
 40  
 41  _EqOrderType = Union[bool, Callable[[Any], Any]]
 42  _ValidatorType = Callable[[Any, Attribute[_T], _T], Any]
 43  _ConverterType = Callable[[Any], Any]
 44  _FilterType = Callable[[Attribute[_T], _T], bool]
 45  _ReprType = Callable[[Any], str]
 46  _ReprArgType = Union[bool, _ReprType]
 47  _OnSetAttrType = Callable[[Any, Attribute[Any], Any], Any]
 48  _OnSetAttrArgType = Union[
 49      _OnSetAttrType, List[_OnSetAttrType], setters._NoOpType
 50  ]
 51  _FieldTransformer = Callable[
 52      [type, List[Attribute[Any]]], List[Attribute[Any]]
 53  ]
 54  _CompareWithType = Callable[[Any, Any], bool]
 55  # FIXME: in reality, if multiple validators are passed they must be in a list
 56  # or tuple, but those are invariant and so would prevent subtypes of
 57  # _ValidatorType from working when passed in a list or tuple.
 58  _ValidatorArgType = Union[_ValidatorType[_T], Sequence[_ValidatorType[_T]]]
 59  
 60  # _make --
 61  
 62  NOTHING: object
 63  
 64  # NOTE: Factory lies about its return type to make this possible:
 65  # `x: List[int] # = Factory(list)`
 66  # Work around mypy issue #4554 in the common case by using an overload.
 67  if sys.version_info >= (3, 8):
 68      from typing import Literal
 69      @overload
 70      def Factory(factory: Callable[[], _T]) -> _T: ...
 71      @overload
 72      def Factory(
 73          factory: Callable[[Any], _T],
 74          takes_self: Literal[True],
 75      ) -> _T: ...
 76      @overload
 77      def Factory(
 78          factory: Callable[[], _T],
 79          takes_self: Literal[False],
 80      ) -> _T: ...
 81  
 82  else:
 83      @overload
 84      def Factory(factory: Callable[[], _T]) -> _T: ...
 85      @overload
 86      def Factory(
 87          factory: Union[Callable[[Any], _T], Callable[[], _T]],
 88          takes_self: bool = ...,
 89      ) -> _T: ...
 90  
 91  # Static type inference support via __dataclass_transform__ implemented as per:
 92  # https://github.com/microsoft/pyright/blob/1.1.135/specs/dataclass_transforms.md
 93  # This annotation must be applied to all overloads of "define" and "attrs"
 94  #
 95  # NOTE: This is a typing construct and does not exist at runtime.  Extensions
 96  # wrapping attrs decorators should declare a separate __dataclass_transform__
 97  # signature in the extension module using the specification linked above to
 98  # provide pyright support.
 99  def __dataclass_transform__(
100      *,
101      eq_default: bool = True,
102      order_default: bool = False,
103      kw_only_default: bool = False,
104      field_descriptors: Tuple[Union[type, Callable[..., Any]], ...] = (()),
105  ) -> Callable[[_T], _T]: ...
106  
107  class Attribute(Generic[_T]):
108      name: str
109      default: Optional[_T]
110      validator: Optional[_ValidatorType[_T]]
111      repr: _ReprArgType
112      cmp: _EqOrderType
113      eq: _EqOrderType
114      order: _EqOrderType
115      hash: Optional[bool]
116      init: bool
117      converter: Optional[_ConverterType]
118      metadata: Dict[Any, Any]
119      type: Optional[Type[_T]]
120      kw_only: bool
121      on_setattr: _OnSetAttrType
122      def evolve(self, **changes: Any) -> "Attribute[Any]": ...
123  
124  # NOTE: We had several choices for the annotation to use for type arg:
125  # 1) Type[_T]
126  #   - Pros: Handles simple cases correctly
127  #   - Cons: Might produce less informative errors in the case of conflicting
128  #     TypeVars e.g. `attr.ib(default='bad', type=int)`
129  # 2) Callable[..., _T]
130  #   - Pros: Better error messages than #1 for conflicting TypeVars
131  #   - Cons: Terrible error messages for validator checks.
132  #   e.g. attr.ib(type=int, validator=validate_str)
133  #        -> error: Cannot infer function type argument
134  # 3) type (and do all of the work in the mypy plugin)
135  #   - Pros: Simple here, and we could customize the plugin with our own errors.
136  #   - Cons: Would need to write mypy plugin code to handle all the cases.
137  # We chose option #1.
138  
139  # `attr` lies about its return type to make the following possible:
140  #     attr()    -> Any
141  #     attr(8)   -> int
142  #     attr(validator=<some callable>)  -> Whatever the callable expects.
143  # This makes this type of assignments possible:
144  #     x: int = attr(8)
145  #
146  # This form catches explicit None or no default but with no other arguments
147  # returns Any.
148  @overload
149  def attrib(
150      default: None = ...,
151      validator: None = ...,
152      repr: _ReprArgType = ...,
153      cmp: Optional[_EqOrderType] = ...,
154      hash: Optional[bool] = ...,
155      init: bool = ...,
156      metadata: Optional[Mapping[Any, Any]] = ...,
157      type: None = ...,
158      converter: None = ...,
159      factory: None = ...,
160      kw_only: bool = ...,
161      eq: Optional[_EqOrderType] = ...,
162      order: Optional[_EqOrderType] = ...,
163      on_setattr: Optional[_OnSetAttrArgType] = ...,
164  ) -> Any: ...
165  
166  # This form catches an explicit None or no default and infers the type from the
167  # other arguments.
168  @overload
169  def attrib(
170      default: None = ...,
171      validator: Optional[_ValidatorArgType[_T]] = ...,
172      repr: _ReprArgType = ...,
173      cmp: Optional[_EqOrderType] = ...,
174      hash: Optional[bool] = ...,
175      init: bool = ...,
176      metadata: Optional[Mapping[Any, Any]] = ...,
177      type: Optional[Type[_T]] = ...,
178      converter: Optional[_ConverterType] = ...,
179      factory: Optional[Callable[[], _T]] = ...,
180      kw_only: bool = ...,
181      eq: Optional[_EqOrderType] = ...,
182      order: Optional[_EqOrderType] = ...,
183      on_setattr: Optional[_OnSetAttrArgType] = ...,
184  ) -> _T: ...
185  
186  # This form catches an explicit default argument.
187  @overload
188  def attrib(
189      default: _T,
190      validator: Optional[_ValidatorArgType[_T]] = ...,
191      repr: _ReprArgType = ...,
192      cmp: Optional[_EqOrderType] = ...,
193      hash: Optional[bool] = ...,
194      init: bool = ...,
195      metadata: Optional[Mapping[Any, Any]] = ...,
196      type: Optional[Type[_T]] = ...,
197      converter: Optional[_ConverterType] = ...,
198      factory: Optional[Callable[[], _T]] = ...,
199      kw_only: bool = ...,
200      eq: Optional[_EqOrderType] = ...,
201      order: Optional[_EqOrderType] = ...,
202      on_setattr: Optional[_OnSetAttrArgType] = ...,
203  ) -> _T: ...
204  
205  # This form covers type=non-Type: e.g. forward references (str), Any
206  @overload
207  def attrib(
208      default: Optional[_T] = ...,
209      validator: Optional[_ValidatorArgType[_T]] = ...,
210      repr: _ReprArgType = ...,
211      cmp: Optional[_EqOrderType] = ...,
212      hash: Optional[bool] = ...,
213      init: bool = ...,
214      metadata: Optional[Mapping[Any, Any]] = ...,
215      type: object = ...,
216      converter: Optional[_ConverterType] = ...,
217      factory: Optional[Callable[[], _T]] = ...,
218      kw_only: bool = ...,
219      eq: Optional[_EqOrderType] = ...,
220      order: Optional[_EqOrderType] = ...,
221      on_setattr: Optional[_OnSetAttrArgType] = ...,
222  ) -> Any: ...
223  @overload
224  def field(
225      *,
226      default: None = ...,
227      validator: None = ...,
228      repr: _ReprArgType = ...,
229      hash: Optional[bool] = ...,
230      init: bool = ...,
231      metadata: Optional[Mapping[Any, Any]] = ...,
232      converter: None = ...,
233      factory: None = ...,
234      kw_only: bool = ...,
235      eq: Optional[bool] = ...,
236      order: Optional[bool] = ...,
237      on_setattr: Optional[_OnSetAttrArgType] = ...,
238  ) -> Any: ...
239  
240  # This form catches an explicit None or no default and infers the type from the
241  # other arguments.
242  @overload
243  def field(
244      *,
245      default: None = ...,
246      validator: Optional[_ValidatorArgType[_T]] = ...,
247      repr: _ReprArgType = ...,
248      hash: Optional[bool] = ...,
249      init: bool = ...,
250      metadata: Optional[Mapping[Any, Any]] = ...,
251      converter: Optional[_ConverterType] = ...,
252      factory: Optional[Callable[[], _T]] = ...,
253      kw_only: bool = ...,
254      eq: Optional[_EqOrderType] = ...,
255      order: Optional[_EqOrderType] = ...,
256      on_setattr: Optional[_OnSetAttrArgType] = ...,
257  ) -> _T: ...
258  
259  # This form catches an explicit default argument.
260  @overload
261  def field(
262      *,
263      default: _T,
264      validator: Optional[_ValidatorArgType[_T]] = ...,
265      repr: _ReprArgType = ...,
266      hash: Optional[bool] = ...,
267      init: bool = ...,
268      metadata: Optional[Mapping[Any, Any]] = ...,
269      converter: Optional[_ConverterType] = ...,
270      factory: Optional[Callable[[], _T]] = ...,
271      kw_only: bool = ...,
272      eq: Optional[_EqOrderType] = ...,
273      order: Optional[_EqOrderType] = ...,
274      on_setattr: Optional[_OnSetAttrArgType] = ...,
275  ) -> _T: ...
276  
277  # This form covers type=non-Type: e.g. forward references (str), Any
278  @overload
279  def field(
280      *,
281      default: Optional[_T] = ...,
282      validator: Optional[_ValidatorArgType[_T]] = ...,
283      repr: _ReprArgType = ...,
284      hash: Optional[bool] = ...,
285      init: bool = ...,
286      metadata: Optional[Mapping[Any, Any]] = ...,
287      converter: Optional[_ConverterType] = ...,
288      factory: Optional[Callable[[], _T]] = ...,
289      kw_only: bool = ...,
290      eq: Optional[_EqOrderType] = ...,
291      order: Optional[_EqOrderType] = ...,
292      on_setattr: Optional[_OnSetAttrArgType] = ...,
293  ) -> Any: ...
294  @overload
295  @__dataclass_transform__(order_default=True, field_descriptors=(attrib, field))
296  def attrs(
297      maybe_cls: _C,
298      these: Optional[Dict[str, Any]] = ...,
299      repr_ns: Optional[str] = ...,
300      repr: bool = ...,
301      cmp: Optional[_EqOrderType] = ...,
302      hash: Optional[bool] = ...,
303      init: bool = ...,
304      slots: bool = ...,
305      frozen: bool = ...,
306      weakref_slot: bool = ...,
307      str: bool = ...,
308      auto_attribs: bool = ...,
309      kw_only: bool = ...,
310      cache_hash: bool = ...,
311      auto_exc: bool = ...,
312      eq: Optional[_EqOrderType] = ...,
313      order: Optional[_EqOrderType] = ...,
314      auto_detect: bool = ...,
315      collect_by_mro: bool = ...,
316      getstate_setstate: Optional[bool] = ...,
317      on_setattr: Optional[_OnSetAttrArgType] = ...,
318      field_transformer: Optional[_FieldTransformer] = ...,
319      match_args: bool = ...,
320  ) -> _C: ...
321  @overload
322  @__dataclass_transform__(order_default=True, field_descriptors=(attrib, field))
323  def attrs(
324      maybe_cls: None = ...,
325      these: Optional[Dict[str, Any]] = ...,
326      repr_ns: Optional[str] = ...,
327      repr: bool = ...,
328      cmp: Optional[_EqOrderType] = ...,
329      hash: Optional[bool] = ...,
330      init: bool = ...,
331      slots: bool = ...,
332      frozen: bool = ...,
333      weakref_slot: bool = ...,
334      str: bool = ...,
335      auto_attribs: bool = ...,
336      kw_only: bool = ...,
337      cache_hash: bool = ...,
338      auto_exc: bool = ...,
339      eq: Optional[_EqOrderType] = ...,
340      order: Optional[_EqOrderType] = ...,
341      auto_detect: bool = ...,
342      collect_by_mro: bool = ...,
343      getstate_setstate: Optional[bool] = ...,
344      on_setattr: Optional[_OnSetAttrArgType] = ...,
345      field_transformer: Optional[_FieldTransformer] = ...,
346      match_args: bool = ...,
347  ) -> Callable[[_C], _C]: ...
348  @overload
349  @__dataclass_transform__(field_descriptors=(attrib, field))
350  def define(
351      maybe_cls: _C,
352      *,
353      these: Optional[Dict[str, Any]] = ...,
354      repr: bool = ...,
355      hash: Optional[bool] = ...,
356      init: bool = ...,
357      slots: bool = ...,
358      frozen: bool = ...,
359      weakref_slot: bool = ...,
360      str: bool = ...,
361      auto_attribs: bool = ...,
362      kw_only: bool = ...,
363      cache_hash: bool = ...,
364      auto_exc: bool = ...,
365      eq: Optional[bool] = ...,
366      order: Optional[bool] = ...,
367      auto_detect: bool = ...,
368      getstate_setstate: Optional[bool] = ...,
369      on_setattr: Optional[_OnSetAttrArgType] = ...,
370      field_transformer: Optional[_FieldTransformer] = ...,
371      match_args: bool = ...,
372  ) -> _C: ...
373  @overload
374  @__dataclass_transform__(field_descriptors=(attrib, field))
375  def define(
376      maybe_cls: None = ...,
377      *,
378      these: Optional[Dict[str, Any]] = ...,
379      repr: bool = ...,
380      hash: Optional[bool] = ...,
381      init: bool = ...,
382      slots: bool = ...,
383      frozen: bool = ...,
384      weakref_slot: bool = ...,
385      str: bool = ...,
386      auto_attribs: bool = ...,
387      kw_only: bool = ...,
388      cache_hash: bool = ...,
389      auto_exc: bool = ...,
390      eq: Optional[bool] = ...,
391      order: Optional[bool] = ...,
392      auto_detect: bool = ...,
393      getstate_setstate: Optional[bool] = ...,
394      on_setattr: Optional[_OnSetAttrArgType] = ...,
395      field_transformer: Optional[_FieldTransformer] = ...,
396      match_args: bool = ...,
397  ) -> Callable[[_C], _C]: ...
398  
399  mutable = define
400  frozen = define  # they differ only in their defaults
401  
402  # TODO: add support for returning NamedTuple from the mypy plugin
403  class _Fields(Tuple[Attribute[Any], ...]):
404      def __getattr__(self, name: str) -> Attribute[Any]: ...
405  
406  def fields(cls: type) -> _Fields: ...
407  def fields_dict(cls: type) -> Dict[str, Attribute[Any]]: ...
408  def validate(inst: Any) -> None: ...
409  def resolve_types(
410      cls: _C,
411      globalns: Optional[Dict[str, Any]] = ...,
412      localns: Optional[Dict[str, Any]] = ...,
413      attribs: Optional[List[Attribute[Any]]] = ...,
414  ) -> _C: ...
415  
416  # TODO: add support for returning a proper attrs class from the mypy plugin
417  # we use Any instead of _CountingAttr so that e.g. `make_class('Foo',
418  # [attr.ib()])` is valid
419  def make_class(
420      name: str,
421      attrs: Union[List[str], Tuple[str, ...], Dict[str, Any]],
422      bases: Tuple[type, ...] = ...,
423      repr_ns: Optional[str] = ...,
424      repr: bool = ...,
425      cmp: Optional[_EqOrderType] = ...,
426      hash: Optional[bool] = ...,
427      init: bool = ...,
428      slots: bool = ...,
429      frozen: bool = ...,
430      weakref_slot: bool = ...,
431      str: bool = ...,
432      auto_attribs: bool = ...,
433      kw_only: bool = ...,
434      cache_hash: bool = ...,
435      auto_exc: bool = ...,
436      eq: Optional[_EqOrderType] = ...,
437      order: Optional[_EqOrderType] = ...,
438      collect_by_mro: bool = ...,
439      on_setattr: Optional[_OnSetAttrArgType] = ...,
440      field_transformer: Optional[_FieldTransformer] = ...,
441  ) -> type: ...
442  
443  # _funcs --
444  
445  # TODO: add support for returning TypedDict from the mypy plugin
446  # FIXME: asdict/astuple do not honor their factory args. Waiting on one of
447  # these:
448  # https://github.com/python/mypy/issues/4236
449  # https://github.com/python/typing/issues/253
450  # XXX: remember to fix attrs.asdict/astuple too!
451  def asdict(
452      inst: Any,
453      recurse: bool = ...,
454      filter: Optional[_FilterType[Any]] = ...,
455      dict_factory: Type[Mapping[Any, Any]] = ...,
456      retain_collection_types: bool = ...,
457      value_serializer: Optional[
458          Callable[[type, Attribute[Any], Any], Any]
459      ] = ...,
460      tuple_keys: Optional[bool] = ...,
461  ) -> Dict[str, Any]: ...
462  
463  # TODO: add support for returning NamedTuple from the mypy plugin
464  def astuple(
465      inst: Any,
466      recurse: bool = ...,
467      filter: Optional[_FilterType[Any]] = ...,
468      tuple_factory: Type[Sequence[Any]] = ...,
469      retain_collection_types: bool = ...,
470  ) -> Tuple[Any, ...]: ...
471  def has(cls: type) -> bool: ...
472  def assoc(inst: _T, **changes: Any) -> _T: ...
473  def evolve(inst: _T, **changes: Any) -> _T: ...
474  
475  # _config --
476  
477  def set_run_validators(run: bool) -> None: ...
478  def get_run_validators() -> bool: ...
479  
480  # aliases --
481  
482  s = attributes = attrs
483  ib = attr = attrib
484  dataclass = attrs  # Technically, partial(attrs, auto_attribs=True) ;)