Type system features
This issue summarizes the support for various type system features in ty. Sections are organized to follow the structure of the Python typing specification , with some additional sections at the end.
If a top-level item is marked completed without any sub-items, you can generally expect that feature to be fully implemented (and we value any bug reports in case you find issues). If a top-level item is marked completed with open sub-items, the feature is generally working, but there might be some open issues — including but not limited to the ones listed (in this case, we also value any bug reports, but please search the issue tracker before doing so). If a top-level item is not checked, the feature is not implemented yet (it's probably not helpful to report bugs, but feel free to upvote the tracking issue or comment if you have useful information).
Special types and type qualifiers
Official documentation
tests: any.md , never.md , int_float_complex.md , final.md , classvar.md , annotated.md , union.md , instance_layout_conflict.md
Any
None
NoReturn, Never
object
Literal[...] (strings, ints, bools, enum, None)
LiteralString
type[C]
float/complex special cases (float means int | float)
Final, Final[T]
@final decorator
@disjoint_base decorator
ClassVar, ClassVar[T]
InitVar[T] (see Dataclasses)
Annotated[T, ...]
Required[T], NotRequired[T] (see TypedDict)
ReadOnly[T] (see TypedDict)
Union[X, Y], X | Y
Optional[X]
type() functional syntax Support type()'s functional syntax #740
Generics
Official documentation
tests: pep695/ , legacy/ , self.md , scoping.md
Protocols
Official documentation
tests: protocols.md
Type narrowing
Official documentation
tests: narrow/ , type_guards.md
Tuples
Official documentation
tests: subscript/tuple.md , comparison/tuples.md , binary/tuples.md
NamedTuple
Official documentation
tests: named_tuple.md
Class syntax (class Foo(NamedTuple): ...)
Field access by name and index, slicing, unpacking
Default values, diagnostic for non-default after default
Read-only fields (assignment rejected)
Inheritance, generic NamedTuples
Multiple inheritance restriction
Underscore field name restriction
Prohibited attribute override check (_asdict, _make, …)
_fields, _field_defaults, _make, _asdict, _replace
Subtype of tuple[...]
super() restriction in NamedTuple methods
NamedTuple in type expressions
type[NamedTuple] in type expressions
Functional syntax (NamedTuple("Foo", [...])) Support the functional syntax for NamedTuples #1049
collections.namedtuple: not tested
Subclass field conflicting with base class field: not tested
TypedDict
Official documentation
tests: typed_dict.md
Class syntax (class Foo(TypedDict): ...)
Key access by literal string, Final constants
Constructor validation (missing keys, invalid types)
total parameter
Required[…], NotRequired[…]
ReadOnly[…]
Inheritance, generic TypedDicts
Recursive TypedDict
Structural assignability and equivalence
Methods (get, pop, setdefault, keys, values, copy)
__total__, __required_keys__, __optional_keys__
Diagnostic: Invalid isinstance() check on TypedDict: not tested
Functional syntax (TypedDict("Foo", {...})) Functional TypedDict syntax #3095
closed, extra_items (PEP 728) Support closed and extra_items for TypedDicts (PEP 728) #3096
Unpack for **kwargs typing Support typing.Unpack #1746
Overriding of fields in inheritance Detect invalid overrides of TypedDict items #3097
Tagged union narrowing Implement "tagged union" narrowing for namedtuples and arbitrary nominal types #1479
Enums
Official documentation
tests: enums.md , comparison/enums.md
Literals
Official documentation
tests: literal.md , literal_string.md
Callables
Official documentation
tests: callable.md , callable_instance.md
Overloads
Official documentation
tests: overloads.md , call/overloads.md
Dataclasses
Official documentation
tests: dataclasses.md , fields.md
@dataclass decorator (init, repr, eq, order, frozen, match_args, kw_only, slots, weakref_slot, unsafe_hash)
field() (default, default_factory, init, kw_only, doc, repr, hash, compare)
InitVar[…], ClassVar[…] exclusion, KW_ONLY sentinel
fields(), __dataclass_fields__
Final fields
Inheritance, generic dataclasses, descriptor-typed fields
replace(), __replace__
asdict()
Diagnostic: frozen/non-frozen dataclass inheritance
Diagnostic: non-default field after default field Advanced dataclass support #111
Diagnostic: order=True with custom comparison methods Advanced dataclass support #111
Diagnostic: frozen=True with __setattr__/__delattr__ Advanced dataclass support #111
__post_init__ signature validation Advanced dataclass support #111
Diagnostic: unsound subclassing of order=True dataclasses Add diagnostic warning about unsound subclassing of order=True dataclasses #1681
Detect slots=True-specific issues in dataclasses Detect slots=True-specific issues in dataclasses #3094
astuple(): not tested
make_dataclass(), is_dataclass(): not tested
dataclass_transform
Official documentation
tests: dataclass_transform.md
Constructors
Official documentation
tests: constructor.md
Type aliases
Official documentation
tests: pep695_type_aliases.md , pep613_type_aliases.md , implicit_type_aliases.md
Type checker directives
Official documentation
tests: directives/
Module resolution, imports, packages
Official documentation
tests: import/
Control flow analysis
tests: terminal_statements.md , exhaustiveness_checking.md , unreachable.md , exception/control_flow.md
Invalid overrides
(Liskov Substitution Principle checks, etc)
tests: liskov.md , override.md
Abstract base classes
tests: return_type.md , overloads.md
__slots__
tests: instance_layout_conflict.md
Special library features
Standard library:
Third-party library support (currently not decided how far we want to go here):
Type system features
This issue summarizes the support for various type system features in ty. Sections are organized to follow the structure of the Python typing specification, with some additional sections at the end.
If a top-level item is marked completed without any sub-items, you can generally expect that feature to be fully implemented (and we value any bug reports in case you find issues). If a top-level item is marked completed with open sub-items, the feature is generally working, but there might be some open issues — including but not limited to the ones listed (in this case, we also value any bug reports, but please search the issue tracker before doing so). If a top-level item is not checked, the feature is not implemented yet (it's probably not helpful to report bugs, but feel free to upvote the tracking issue or comment if you have useful information).
Special types and type qualifiers
Official documentation
tests:
any.md,never.md,int_float_complex.md,final.md,classvar.md,annotated.md,union.md,instance_layout_conflict.mdAnyNoneNoReturn,NeverobjectLiteral[...](strings, ints, bools, enum, None)LiteralStringtype[C]float/complexspecial cases (floatmeansint | float)Final,Final[T]Finalattribute Prevent overriding ofFinalattributes in subclasses #871Finalwithout binding Detect if there is no binding to a symbol declaredFinal#872@finaldecorator@disjoint_basedecoratorClassVar,ClassVar[T]ClassVarwith type variableClassVarshouldn't be allowed to contain type variables #518InitVar[T](see Dataclasses)Annotated[T, ...]Required[T],NotRequired[T](see TypedDict)ReadOnly[T](see TypedDict)Union[X, Y],X | YOptional[X]type()functional syntax Supporttype()'s functional syntax #740Generics
Official documentation
tests:
pep695/,legacy/,self.md,scoping.mdTypeVar(legacy syntax)TypeVar(PEP 695 syntax:def f[T]())TypeVarupper bound (bound=)TypeVarconstraintsTypeVardefaults (PEP 696)TypeVarvariance (covariant,contravariant)TypeVarvariance inference (infer_variance)ParamSpec(legacy and PEP 695 syntax)ParamSpecusage validation Validate more usages ofParamSpec,P.args,P.kwargs#1861ParamSpec.args,ParamSpec.kwargsParamSpecdefaultsSelfSelfin attribute annotations supporttyping.Selfused as attribute (or dataclass field) type #1124typing.Selfin staticmethods and metaclasses should be rejected #1897Self#2758CallablesTypeVarTuplesupport TypeVarTuple #156Protocols
Official documentation
tests:
protocols.mdProtocolclass definitionis_protocol(),get_protocol_members()@runtime_checkabledecorator@propertymembers@propertymembers on protocols #1379@classmethodand@staticmethodmembers Support@staticmethodprotocol members and@classmethodprotocol members #1381ClassVarmembers SupportClassVarprotocol members #1380type[SomeProtocol]Supporttype[SomeProtocol]#903issubclass()on protocols with non-methods Emit diagnostic on issubclass calls against protocols with non-method members #1878Type narrowing
Official documentation
tests:
narrow/,type_guards.mdisinstance()/issubclass()narrowingis None/is not Nonenarrowingis/is notidentity narrowingassertnarrowingmatchstatement narrowinghasattr()narrowingcallable()narrowingTypeIs[…]user-defined type guardsTypeGuard[…]user-defined type guards Support narrowing usingTypeGuard#117TypeIs/TypeGuardas method TypeIs does not work as a method/classmethod #1569Never/NoReturnbetter narrowing from conditional terminals and NoReturn calls #690Tuples
Official documentation
tests:
subscript/tuple.md,comparison/tuples.md,binary/tuples.mdtuple[X, Y, Z]heterogeneous tuplestuple[X, ...]homogeneous tuplestuple[()]empty tupletuple[X, *tuple[Y, ...]])typing.Tuple(deprecated alias)*argsunpacking in callsTypeVarTuple/Unpacksupport TypeVarTuple #156NamedTupleOfficial documentation
tests:
named_tuple.mdclass Foo(NamedTuple): ...)NamedTuples_asdict,_make, …)_fields,_field_defaults,_make,_asdict,_replacetuple[...]super()restriction inNamedTuplemethodsNamedTuplein type expressionstype[NamedTuple]in type expressionsNamedTuple("Foo", [...])) Support the functional syntax for NamedTuples #1049collections.namedtuple: not testedTypedDictOfficial documentation
tests:
typed_dict.mdclass Foo(TypedDict): ...)FinalconstantstotalparameterRequired[…],NotRequired[…]ReadOnly[…]TypedDictsTypedDictget,pop,setdefault,keys,values,copy)__total__,__required_keys__,__optional_keys__isinstance()check onTypedDict: not testedTypedDict("Foo", {...})) FunctionalTypedDictsyntax #3095closed,extra_items(PEP 728) Supportclosedandextra_itemsfor TypedDicts (PEP 728) #3096Unpackfor**kwargstyping Supporttyping.Unpack#1746Enums
Official documentation
tests:
enums.md,comparison/enums.mdEnum,IntEnum,StrEnumLiteral[EnumMember]types.name,.valueinferenceauto()value inferencemember(),nonmember()_ignore_attributeif/match)__eq__/__ne__methodslist(Enum)returnslist[Unknown]Enum("Name", [...])) Enums: advanced features #876enum.Flagexpansion handling Enums: advanced features #876__new__or__init__methods Enums: advanced features #876_generate_next_value_support Enums: advanced features #876Color("red")) Enums: advanced features #876__eq__inmatchIncorrect narrowing of enums with custom__eq__methods inmatchstatements #1454Literals
Official documentation
tests:
literal.md,literal_string.mdLiteral[0](integer literals)Literal["a"](string literals)Literal[b"a"](bytes literals)Literal[True](boolean literals)Literal[Color.RED](enum literals)Literal[None]LiteralflatteningLiteralwith type aliasesLiteralStringLiteralStringassignabilityLiteralStringnarrowingLiteralStringcannot be parameterizedLiteralStringcannot be subclassedCallables
Official documentation
tests:
callable.md,callable_instance.mdCallable[[X, Y], R]syntaxCallable[..., R]gradual formCallablewithParamSpec__call__method)CallabletypesCallablein unions/intersectionsConcatenateSupport Concatenate special form #1535Unpackfor**kwargstyping Supporttyping.Unpack#1746Overloads
Official documentation
tests:
overloads.md,call/overloads.md@overloaddecorator@staticmethod,@classmethod@final/@overrideplacement@overloadwith other decorators No diagnostic reported for bad use of@overrideif the method has other decorators too #1675Dataclasses
Official documentation
tests:
dataclasses.md,fields.md@dataclassdecorator (init,repr,eq,order,frozen,match_args,kw_only,slots,weakref_slot,unsafe_hash)field()(default,default_factory,init,kw_only,doc,repr,hash,compare)InitVar[…],ClassVar[…]exclusion,KW_ONLYsentinelfields(),__dataclass_fields__Finalfieldsreplace(),__replace__replace()returnsUnknownasdict()order=Truewith custom comparison methods Advanced dataclass support #111frozen=Truewith__setattr__/__delattr__Advanced dataclass support #111__post_init__signature validation Advanced dataclass support #111order=Truedataclasses Add diagnostic warning about unsound subclassing oforder=Truedataclasses #1681slots=True-specific issues in dataclasses #3094astuple(): not testedmake_dataclass(),is_dataclass(): not testeddataclass_transformOfficial documentation
tests:
dataclass_transform.md__init_subclass__)eq_defaultparameterorder_defaultparameterkw_only_defaultparameterfrozen_defaultparameterfield_specifiers(init,default,default_factory,factory,kw_only,alias)converterparameterdataclass_transform: feature overview #1327slots, etc.)@dataclass(Home Assistant pattern)__dataclass_{fields,params}__fields are not consideredDataclassInstance#1987Constructors
Official documentation
tests:
constructor.md__init__signature inference__new__signature inference__new__and__init__present__new__/__init____new__return type respect return type of__new__#281__call__Respect signature of metaclass's__call__#2288__new__/__init__consistency validation__init__on instance make it an error to explicitly call__init__on an existing object #1016Type aliases
Official documentation
tests:
pep695_type_aliases.md,pep613_type_aliases.md,implicit_type_aliases.mdAlias = int)TypeAliasannotationtypestatementTypeAliasTypeintrospection (__name__,__value__)Type checker directives
Official documentation
tests:
directives/cast(T, value)castdiagnosticassert_type(value, T)assert_never(value)reveal_type(value)TYPE_CHECKINGconstant@no_type_checkdecoratortype: ignorecommentsty: ignorecomments@deprecateddecorator@overridedecorator@overridedecorator support@typing.override#155Module resolution, imports, packages
Official documentation
tests:
import/.pyi)<package>-stubs)py.typedwithpartial)__all__declarations__all__mutations (.append,.extend,+=)__all__with submodule__all__*) importsimport X as X)py.typedmarker filesconftest.pyresolution (pytest)__builtins__.pyi) Support custom builtins #374.sofiles) improve diagnostics for C extension modules without stubs #487Control flow analysis
tests:
terminal_statements.md,exhaustiveness_checking.md,unreachable.md,exception/control_flow.mdreturn,raise)break,continue)for/whileloop analysistry/except/else/finallycontrol flowfinallylimitations Properly model control flow throughfinallysuites #233Never/NoReturnfunction propagationif/elif/else)match)matchpattern inference Advanced pattern matching support #887assert_never()sys.version_infocomparisonssys.platformchecksmatchstatements Rules for not exhaustivematchcase statements #1060Invalid overrides
(Liskov Substitution Principle checks, etc)
tests:
liskov.md,override.md*args/**kwargscompatibility@staticmethodand@classmethodoverridesinvalid-method-overridediagnostics to cover methods being overridden by non-methods #2156Abstract base classes
tests:
return_type.md,overloads.md@abstractmethoddecorator@abstractmethodwith@overloadvalidationsuper()call to abstract method with trivial body #1923@classmethodor@staticmethodwith trivial body, when accessed on the class object itself #1927__slots__tests:
instance_layout_conflict.md__slots__(string or tuple of strings)__slots__(list, dict, set literals)__slots__support__slots__#1268__slots__support__slots__#1268__slots__name support__slots__#1268__dict__/__weakref__presence validation support__slots__#1268__slots__on builtin subclasses support__slots__#1268Special library features
Standard library:
@cached_propertySupportcached_property#1446functools.partialSupport functools.partial #1536functools.total_orderingAdd support forfunctools.total_ordering#1202Third-party library support (currently not decided how far we want to go here):
attrsadd dedicated support for attrs #2404