codekingpro/portable-devtools
114k
1import enum2import sys3 4from typing import (5 Any,6 Callable,7 Generic,8 Literal,9 Mapping,10 Protocol,11 Sequence,12 TypeVar,13 overload,14)15 16# `import X as X` is required to make these public17from . import converters as converters18from . import exceptions as exceptions19from . import filters as filters20from . import setters as setters21from . import validators as validators22from ._cmp import cmp_using as cmp_using23from ._typing_compat import AttrsInstance_24from ._version_info import VersionInfo25from attrs import (26 define as define,27 field as field,28 mutable as mutable,29 frozen as frozen,30 _EqOrderType,31 _ValidatorType,32 _ConverterType,33 _ReprArgType,34 _OnSetAttrType,35 _OnSetAttrArgType,36 _FieldTransformer,37 _ValidatorArgType,38)39 40if sys.version_info >= (3, 10):41 from typing import TypeGuard, TypeAlias42else:43 from typing_extensions import TypeGuard, TypeAlias44 45if sys.version_info >= (3, 11):46 from typing import dataclass_transform47else:48 from typing_extensions import dataclass_transform49 50__version__: str51__version_info__: VersionInfo52__title__: str53__description__: str54__url__: str55__uri__: str56__author__: str57__email__: str58__license__: str59__copyright__: str60 61_T = TypeVar("_T")62_C = TypeVar("_C", bound=type)63 64_FilterType = Callable[["Attribute[_T]", _T], bool]65 66# We subclass this here to keep the protocol's qualified name clean.67class AttrsInstance(AttrsInstance_, Protocol):68 pass69 70_A = TypeVar("_A", bound=type[AttrsInstance])71 72class _Nothing(enum.Enum):73 NOTHING = enum.auto()74 75NOTHING = _Nothing.NOTHING76NothingType: TypeAlias = Literal[_Nothing.NOTHING]77 78# NOTE: Factory lies about its return type to make this possible:79# `x: List[int] # = Factory(list)`80# Work around mypy issue #4554 in the common case by using an overload.81 82@overload83def Factory(factory: Callable[[], _T]) -> _T: ...84@overload85def Factory(86 factory: Callable[[Any], _T],87 takes_self: Literal[True],88) -> _T: ...89@overload90def Factory(91 factory: Callable[[], _T],92 takes_self: Literal[False],93) -> _T: ...94 95In = TypeVar("In")96Out = TypeVar("Out")97 98class Converter(Generic[In, Out]):99 @overload100 def __init__(self, converter: Callable[[In], Out]) -> None: ...101 @overload102 def __init__(103 self,104 converter: Callable[[In, AttrsInstance, Attribute], Out],105 *,106 takes_self: Literal[True],107 takes_field: Literal[True],108 ) -> None: ...109 @overload110 def __init__(111 self,112 converter: Callable[[In, Attribute], Out],113 *,114 takes_field: Literal[True],115 ) -> None: ...116 @overload117 def __init__(118 self,119 converter: Callable[[In, AttrsInstance], Out],120 *,121 takes_self: Literal[True],122 ) -> None: ...123 124class Attribute(Generic[_T]):125 name: str126 default: _T | None127 validator: _ValidatorType[_T] | None128 repr: _ReprArgType129 cmp: _EqOrderType130 eq: _EqOrderType131 order: _EqOrderType132 hash: bool | None133 init: bool134 converter: Converter | None135 metadata: dict[Any, Any]136 type: type[_T] | None137 kw_only: bool138 on_setattr: _OnSetAttrType139 alias: str | None140 141 def evolve(self, **changes: Any) -> "Attribute[Any]": ...142 143# NOTE: We had several choices for the annotation to use for type arg:144# 1) Type[_T]145# - Pros: Handles simple cases correctly146# - Cons: Might produce less informative errors in the case of conflicting147# TypeVars e.g. `attr.ib(default='bad', type=int)`148# 2) Callable[..., _T]149# - Pros: Better error messages than #1 for conflicting TypeVars150# - Cons: Terrible error messages for validator checks.151# e.g. attr.ib(type=int, validator=validate_str)152# -> error: Cannot infer function type argument153# 3) type (and do all of the work in the mypy plugin)154# - Pros: Simple here, and we could customize the plugin with our own errors.155# - Cons: Would need to write mypy plugin code to handle all the cases.156# We chose option #1.157 158# `attr` lies about its return type to make the following possible:159# attr() -> Any160# attr(8) -> int161# attr(validator=<some callable>) -> Whatever the callable expects.162# This makes this type of assignments possible:163# x: int = attr(8)164#165# This form catches explicit None or no default but with no other arguments166# returns Any.167@overload168def attrib(169 default: None = ...,170 validator: None = ...,171 repr: _ReprArgType = ...,172 cmp: _EqOrderType | None = ...,173 hash: bool | None = ...,174 init: bool = ...,175 metadata: Mapping[Any, Any] | None = ...,176 type: None = ...,177 converter: None = ...,178 factory: None = ...,179 kw_only: bool | None = ...,180 eq: _EqOrderType | None = ...,181 order: _EqOrderType | None = ...,182 on_setattr: _OnSetAttrArgType | None = ...,183 alias: str | None = ...,184) -> Any: ...185 186# This form catches an explicit None or no default and infers the type from the187# other arguments.188@overload189def attrib(190 default: None = ...,191 validator: _ValidatorArgType[_T] | None = ...,192 repr: _ReprArgType = ...,193 cmp: _EqOrderType | None = ...,194 hash: bool | None = ...,195 init: bool = ...,196 metadata: Mapping[Any, Any] | None = ...,197 type: type[_T] | None = ...,198 converter: _ConverterType199 | list[_ConverterType]200 | tuple[_ConverterType]201 | None = ...,202 factory: Callable[[], _T] | None = ...,203 kw_only: bool | None = ...,204 eq: _EqOrderType | None = ...,205 order: _EqOrderType | None = ...,206 on_setattr: _OnSetAttrArgType | None = ...,207 alias: str | None = ...,208) -> _T: ...209 210# This form catches an explicit default argument.211@overload212def attrib(213 default: _T,214 validator: _ValidatorArgType[_T] | None = ...,215 repr: _ReprArgType = ...,216 cmp: _EqOrderType | None = ...,217 hash: bool | None = ...,218 init: bool = ...,219 metadata: Mapping[Any, Any] | None = ...,220 type: type[_T] | None = ...,221 converter: _ConverterType222 | list[_ConverterType]223 | tuple[_ConverterType]224 | None = ...,225 factory: Callable[[], _T] | None = ...,226 kw_only: bool | None = ...,227 eq: _EqOrderType | None = ...,228 order: _EqOrderType | None = ...,229 on_setattr: _OnSetAttrArgType | None = ...,230 alias: str | None = ...,231) -> _T: ...232 233# This form covers type=non-Type: e.g. forward references (str), Any234@overload235def attrib(236 default: _T | None = ...,237 validator: _ValidatorArgType[_T] | None = ...,238 repr: _ReprArgType = ...,239 cmp: _EqOrderType | None = ...,240 hash: bool | None = ...,241 init: bool = ...,242 metadata: Mapping[Any, Any] | None = ...,243 type: object = ...,244 converter: _ConverterType245 | list[_ConverterType]246 | tuple[_ConverterType]247 | None = ...,248 factory: Callable[[], _T] | None = ...,249 kw_only: bool | None = ...,250 eq: _EqOrderType | None = ...,251 order: _EqOrderType | None = ...,252 on_setattr: _OnSetAttrArgType | None = ...,253 alias: str | None = ...,254) -> Any: ...255@overload256@dataclass_transform(order_default=True, field_specifiers=(attrib, field))257def attrs(258 maybe_cls: _C,259 these: dict[str, Any] | None = ...,260 repr_ns: str | None = ...,261 repr: bool = ...,262 cmp: _EqOrderType | None = ...,263 hash: bool | None = ...,264 init: bool = ...,265 slots: bool = ...,266 frozen: bool = ...,267 weakref_slot: bool = ...,268 str: bool = ...,269 auto_attribs: bool = ...,270 kw_only: bool = ...,271 cache_hash: bool = ...,272 auto_exc: bool = ...,273 eq: _EqOrderType | None = ...,274 order: _EqOrderType | None = ...,275 auto_detect: bool = ...,276 collect_by_mro: bool = ...,277 getstate_setstate: bool | None = ...,278 on_setattr: _OnSetAttrArgType | None = ...,279 field_transformer: _FieldTransformer | None = ...,280 match_args: bool = ...,281 unsafe_hash: bool | None = ...,282) -> _C: ...283@overload284@dataclass_transform(order_default=True, field_specifiers=(attrib, field))285def attrs(286 maybe_cls: None = ...,287 these: dict[str, Any] | None = ...,288 repr_ns: str | None = ...,289 repr: bool = ...,290 cmp: _EqOrderType | None = ...,291 hash: bool | None = ...,292 init: bool = ...,293 slots: bool = ...,294 frozen: bool = ...,295 weakref_slot: bool = ...,296 str: bool = ...,297 auto_attribs: bool = ...,298 kw_only: bool = ...,299 cache_hash: bool = ...,300 auto_exc: bool = ...,301 eq: _EqOrderType | None = ...,302 order: _EqOrderType | None = ...,303 auto_detect: bool = ...,304 collect_by_mro: bool = ...,305 getstate_setstate: bool | None = ...,306 on_setattr: _OnSetAttrArgType | None = ...,307 field_transformer: _FieldTransformer | None = ...,308 match_args: bool = ...,309 unsafe_hash: bool | None = ...,310) -> Callable[[_C], _C]: ...311def fields(cls: type[AttrsInstance] | AttrsInstance) -> Any: ...312def fields_dict(cls: type[AttrsInstance]) -> dict[str, Attribute[Any]]: ...313def validate(inst: AttrsInstance) -> None: ...314def resolve_types(315 cls: _A,316 globalns: dict[str, Any] | None = ...,317 localns: dict[str, Any] | None = ...,318 attribs: list[Attribute[Any]] | None = ...,319 include_extras: bool = ...,320) -> _A: ...321 322# TODO: add support for returning a proper attrs class from the mypy plugin323# we use Any instead of _CountingAttr so that e.g. `make_class('Foo',324# [attr.ib()])` is valid325def make_class(326 name: str,327 attrs: list[str] | tuple[str, ...] | dict[str, Any],328 bases: tuple[type, ...] = ...,329 class_body: dict[str, Any] | None = ...,330 repr_ns: str | None = ...,331 repr: bool = ...,332 cmp: _EqOrderType | None = ...,333 hash: bool | None = ...,334 init: bool = ...,335 slots: bool = ...,336 frozen: bool = ...,337 weakref_slot: bool = ...,338 str: bool = ...,339 auto_attribs: bool = ...,340 kw_only: bool = ...,341 cache_hash: bool = ...,342 auto_exc: bool = ...,343 eq: _EqOrderType | None = ...,344 order: _EqOrderType | None = ...,345 collect_by_mro: bool = ...,346 on_setattr: _OnSetAttrArgType | None = ...,347 field_transformer: _FieldTransformer | None = ...,348) -> type: ...349 350# _funcs --351 352# TODO: add support for returning TypedDict from the mypy plugin353# FIXME: asdict/astuple do not honor their factory args. Waiting on one of354# these:355# https://github.com/python/mypy/issues/4236356# https://github.com/python/typing/issues/253357# XXX: remember to fix attrs.asdict/astuple too!358def asdict(359 inst: AttrsInstance,360 recurse: bool = ...,361 filter: _FilterType[Any] | None = ...,362 dict_factory: type[Mapping[Any, Any]] = ...,363 retain_collection_types: bool = ...,364 value_serializer: Callable[[type, Attribute[Any], Any], Any] | None = ...,365 tuple_keys: bool | None = ...,366) -> dict[str, Any]: ...367 368# TODO: add support for returning NamedTuple from the mypy plugin369def astuple(370 inst: AttrsInstance,371 recurse: bool = ...,372 filter: _FilterType[Any] | None = ...,373 tuple_factory: type[Sequence[Any]] = ...,374 retain_collection_types: bool = ...,375) -> tuple[Any, ...]: ...376def has(cls: type) -> TypeGuard[type[AttrsInstance]]: ...377def assoc(inst: _T, **changes: Any) -> _T: ...378def evolve(inst: _T, **changes: Any) -> _T: ...379 380# _config --381 382def set_run_validators(run: bool) -> None: ...383def get_run_validators() -> bool: ...384 385# aliases --386 387s = attributes = attrs388ib = attr = attrib389dataclass = attrs # Technically, partial(attrs, auto_attribs=True) ;)390 