__init__.pyi 17 KB

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