-
Notifications
You must be signed in to change notification settings - Fork 216
Description
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
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/complexspecial cases (floatmeansint | float) -
Final,Final[T]- Diagnostic: subclass overrides
Finalattribute Prevent overriding ofFinalattributes in subclasses #871 - Diagnostic:
Finalwithout binding Detect if there is no binding to a symbol declaredFinal#872
- Diagnostic: subclass overrides
-
@finaldecorator -
@disjoint_basedecorator -
ClassVar,ClassVar[T]- Diagnostic:
ClassVarwith type variableClassVarshouldn't be allowed to contain type variables #518
- Diagnostic:
-
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 Supporttype()'s functional syntax #740
Generics
tests: pep695/, legacy/, self.md, scoping.md
-
TypeVar(legacy syntax) -
TypeVar(PEP 695 syntax:def f[T]()) -
TypeVarupper bound (bound=) -
TypeVarconstraints -
TypeVardefaults (PEP 696) -
TypeVarvariance (covariant,contravariant) -
TypeVarvariance inference (infer_variance) - Generic classes (legacy and PEP 695 syntax)
- Generic functions (legacy and PEP 695 syntax)
- Generic type aliases (PEP 695)
- Some limitations Cannot solve generics involving PEP 695 type aliases #1851
-
ParamSpec(legacy and PEP 695 syntax)-
ParamSpecusage validation Validate more usages ofParamSpec,P.args,P.kwargs#1861
-
-
ParamSpec.args,ParamSpec.kwargs -
ParamSpecdefaults -
Self - Solve type variables in all cases improve typevar solving #623
- Generic classes
- Unions
-
Callables - Generic protocols support generic protocols in typevar solving #1714
- Generic bounds/constraints on type variables Bounds and constraints of type variables cannot be generic #1839
- Support
TypeVarTuplesupport TypeVarTuple #156
Protocols
tests: protocols.md
-
Protocolclass definition - Generic protocols (legacy and PEP 695 syntax)
- Structural subtyping / assignability
- Protocol inheritance
-
is_protocol(),get_protocol_members() -
@runtime_checkabledecorator - Protocol instantiation restriction
- Non-protocol class inheritance restriction
-
@propertymembers- Partial support Properly support
@propertymembers on protocols #1379
- Partial support Properly support
- Modules as protocol implementations
- Method members have some issues Type checker fails to recognize a module as a valid implementation of a Protocol #931
-
@classmethodand@staticmethodmembers Support@staticmethodprotocol members and@classmethodprotocol members #1381 -
ClassVarmembers SupportClassVarprotocol members #1380 -
type[SomeProtocol]Supporttype[SomeProtocol]#903 -
issubclass()on protocols with non-methods Emit diagnostic on issubclass calls against protocols with non-method members #1878
Type narrowing
tests: narrow/, type_guards.md
-
isinstance()/issubclass()narrowing -
is None/is not Nonenarrowing -
is/is notidentity narrowing - Truthiness narrowing
-
assertnarrowing -
matchstatement narrowing -
hasattr()narrowing -
callable()narrowing - Assignment narrowing
-
TypeIs[…]user-defined type guards -
TypeGuard[…]user-defined type guards Support narrowing usingTypeGuard#117 -
TypeIs/TypeGuardas method TypeIs does not work as a method/classmethod #1569 - Tuple length checks Support narrowing on tuple length checks #560
- Tuple match case narrowing Support narrowing on tuple match cases #561
- Narrowing after calls to functions returning
Never/NoReturnbetter narrowing from conditional terminals and NoReturn calls #690
Tuples
tests: subscript/tuple.md, comparison/tuples.md, binary/tuples.md
-
tuple[X, Y, Z]heterogeneous tuples -
tuple[X, ...]homogeneous tuples -
tuple[()]empty tuple - Mixed tuples (
tuple[X, *tuple[Y, ...]]) - Indexing with literal integers
- Diagnostic: index out of bounds
- Slicing tuples
- Tuple subclasses
-
typing.Tuple(deprecated alias) - Covariant element types
- Tuple inheritance
- Unpacking in assignments
-
*argsunpacking in calls - Diagnostic: invalid comparisons for non-fixed-length tuples Emit diagnostics for unsupported comparisons involving non-fixed-length tuples #1741
-
TypeVarTuple/Unpacksupport TypeVarTuple #156 - Intersection of fixed-length tuple with another type should be unpackable like the fixed-length tuple #1978
NamedTuple
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 inNamedTuplemethods -
NamedTuplein type expressions -
type[NamedTuple]in type expressions- Not fully supported
- 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
tests: typed_dict.md
- Class syntax (
class Foo(TypedDict): ...) - Key access by literal string,
Finalconstants - Constructor validation (missing keys, invalid types)
-
totalparameter -
Required[…],NotRequired[…] -
ReadOnly[…] - Inheritance, generic
TypedDicts - Recursive
TypedDict - Structural assignability and equivalence
- Methods (
get,pop,setdefault,keys,values,copy) -
__total__,__required_keys__,__optional_keys__ - Functional syntax (
TypedDict("Foo", {...})) support TypedDict (and Required, NotRequired, ReadOnly) #154 -
closed,extra_items(PEP 728) support TypedDict (and Required, NotRequired, ReadOnly) #154 -
Unpackfor**kwargstyping Supporttyping.Unpack#1746 - Tagged union narrowing Implement "tagged union" narrowing for namedtuples and arbitrary nominal types #1479
- Diagnostic: Invalid
isinstance()check onTypedDict: not tested
Enums
tests: enums.md, comparison/enums.md
-
Enum,IntEnum,StrEnum -
Literal[EnumMember]types -
.name,.valueinference -
auto()value inference -
member(),nonmember() - Enum aliases
-
_ignore_attribute- List form not fully supported
- Implicitly final (subclassing restriction)
- Exhaustiveness checking (
if/match) - Custom
__eq__/__ne__methods - Iteration over enum members
-
list(Enum)returnslist[Unknown]
-
- Functional syntax (
Enum("Name", [...])) Enums: advanced features #876 -
enum.Flagexpansion handling Enums: advanced features #876 - Custom
__new__or__init__methods Enums: advanced features #876 -
_generate_next_value_support Enums: advanced features #876 - Value-based member retrieval (
Color("red")) Enums: advanced features #876 - Narrowing with custom
__eq__inmatchIncorrect narrowing of enums with custom__eq__methods inmatchstatements #1454
Literals
tests: literal.md, literal_string.md
-
Literal[0](integer literals) -
Literal["a"](string literals) -
Literal[b"a"](bytes literals) -
Literal[True](boolean literals) -
Literal[Color.RED](enum literals) -
Literal[None] - Nested
Literalflattening - Union of literals simplification
-
Literalwith type aliases - Invalid form diagnostics
-
LiteralString -
LiteralStringassignability -
LiteralStringnarrowing -
LiteralStringcannot be parameterized -
LiteralStringcannot be subclassed
Callables
tests: callable.md, callable_instance.md
-
Callable[[X, Y], R]syntax -
Callable[..., R]gradual form -
CallablewithParamSpec - Callback protocols (
__call__method) - Callable assignability (contra/covariance)
- Nested
Callabletypes -
Callablein unions/intersections - Invalid form diagnostics
-
ConcatenateSupport Concatenate special form #1535 -
Unpackfor**kwargstyping Supporttyping.Unpack#1746
Overloads
tests: overloads.md, call/overloads.md
-
@overloaddecorator - Overload resolution
- Generic overloads
- Methods, constructors,
@staticmethod,@classmethod - Version-specific overloads
- Diagnostic: at least two overloads required
- Diagnostic: missing implementation (non-stub)
- Diagnostic: inconsistent decorators
- Diagnostic:
@final/@overrideplacement - Variadic parameters with generics Correctly handle variadic parameters for overload step 5 filtering #1825
- Unannotated implementation validation: not tested report invalid overload implementation when implementation is unannotated #1232
- Diagnostic: overlapping overloads Check for overlapping overloads #103
- Implementation consistency check Check implementation consistency for an overloaded function #109
-
@overloadwith other decorators No diagnostic reported for bad use of@overrideif the method has other decorators too #1675
Dataclasses
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_ONLYsentinel -
fields(),__dataclass_fields__ -
Finalfields - Inheritance, generic dataclasses, descriptor-typed fields
-
replace(),__replace__-
replace()returnsUnknown
-
-
asdict()- Incorrectly accepts class objects
- Diagnostic: frozen/non-frozen dataclass inheritance
- Diagnostic: non-default field after default field Advanced dataclass support #111
- Diagnostic:
order=Truewith custom comparison methods Advanced dataclass support #111 - Diagnostic:
frozen=Truewith__setattr__/__delattr__Advanced dataclass support #111 -
__post_init__signature validation Advanced dataclass support #111 - Diagnostic: unsound subclassing of
order=Truedataclasses Add diagnostic warning about unsound subclassing oforder=Truedataclasses #1681 -
astuple(): not tested -
make_dataclass(),is_dataclass(): not tested
dataclass_transform
tests: dataclass_transform.md
- Function-based transformers (decorator functions)
- Metaclass-based transformers
- Base-class-based transformers (
__init_subclass__) -
eq_defaultparameter -
order_defaultparameter -
kw_only_defaultparameter -
frozen_defaultparameter- Metaclass override not working
-
field_specifiers(init,default,default_factory,factory,kw_only,alias)-
converterparameterdataclass_transform: feature overview #1327
-
- Other dataclass parameters (
slots, etc.) - Overloaded dataclass-like decorators
- Nested dataclass-transformers
- Combining with
@dataclass(Home Assistant pattern) - Custom dataclasses with
__dataclass_{fields,params}__fields are not consideredDataclassInstance#1987
Constructors
tests: constructor.md
-
__init__signature inference -
__new__signature inference - Constructor inheritance from superclass
- Both
__new__and__init__present - Descriptor-based
__new__/__init__ - Generic class constructor inference
- Type variable solving from constructor params
- Custom
__new__return type respect return type of__new__#281 - Custom metaclass
__call__Respect signature of metaclass's__call__#2288 -
__new__/__init__consistency validation - Diagnostic: explicit
__init__on instance make it an error to explicitly call__init__on an existing object #1016
Type aliases
tests: pep695_type_aliases.md, pep613_type_aliases.md, implicit_type_aliases.md
- Implicit type aliases (
Alias = int) - PEP 613
TypeAliasannotation- Fully stringified RHS not supported
- PEP 695
typestatement - Generic type aliases (PEP 695)
- Generic implicit/PEP 613 aliases
-
TypeAliasTypeintrospection (__name__,__value__) - Self-referential generic aliases Support self-referential generic implicit/PEP-613 type aliases #1738
Type checker directives
tests: directives/
-
cast(T, value) - Redundant
castdiagnostic -
assert_type(value, T) -
assert_never(value) -
reveal_type(value) -
TYPE_CHECKINGconstant -
@no_type_checkdecorator -
type: ignorecomments -
ty: ignorecomments -
@deprecateddecorator -
@overridedecorator- Diagnostic: override without
@overridedecorator support@typing.override#155
- Diagnostic: override without
Module resolution, imports, packages
tests: import/
- Stub files (
.pyi) - Stub packages (
<package>-stubs) - Partial stub packages (
py.typedwithpartial) - Namespace packages (PEP 420)
- Relative imports
-
__all__declarations -
__all__mutations (.append,.extend,+=) -
__all__with submodule__all__ - Wildcard (
*) imports - Wildcard imports in stubs re-export
- Re-export conventions (
import X as X) - Conditional re-exports in stub files
- Reachability constraints in imports
- Cyclic imports
-
py.typedmarker files -
conftest.pyresolution (pytest) - conda/pixi environment support
- PEP 723 inline script metadata Support single-file scripts with PEP 723 metadata #691
- Custom builtins (
__builtins__.pyi) Support custom builtins #374 - Mono-repository support CLI: Mono-repository support #819
- Compiled extensions (
.sofiles) improve diagnostics for C extension modules without stubs #487 - Per-library import suppression Support for ignoring unresolved-import per library #1354
Control flow analysis
tests: terminal_statements.md, exhaustiveness_checking.md, unreachable.md, exception/control_flow.md
- Terminal statements (
return,raise) - Loop control flow (
break,continue) -
for/whileloop analysis -
try/except/else/finallycontrol flow-
finallylimitations Properly model control flow throughfinallysuites #233
-
-
Never/NoReturnfunction propagation - Exhaustiveness checking (
if/elif/else) - Exhaustiveness checking (
match) - Advanced
matchpattern inference Advanced pattern matching support #887 -
assert_never() -
sys.version_infocomparisons -
sys.platformchecks - Statically known branches
- Return type inference Return type inference #128
- Walrus operator in boolean expressions correctly model short-circuting control flow in boolean expressions #626
- Cyclic control flow (loop back edges) cyclic control flow for loops #232
- Gray out unreachable code Gray out unreachable code #784
- Opt-in rule enforcing exhaustive
matchstatements Rules for not exhaustivematchcase statements #1060 - Opt-in equivalent of mypy's strict-equality check strict-equality #576
- Warn on (accidentally) unreachable code blocks #1948
Invalid overrides
(Liskov Substitution Principle checks, etc)
tests: liskov.md, override.md
- Covariant return types
- Contravariant parameter types
- Invariant mutable attributes
- Full class hierarchy checked
- Positional/keyword parameter kind changes
- Additional optional parameters
-
*args/**kwargscompatibility -
@staticmethodand@classmethodoverrides - Synthesized method overrides (dataclasses)
- Method overridden by non-method Extend
invalid-method-overridediagnostics to cover methods being overridden by non-methods #2156 - Non-method overridden by non-method Enforce the Liskov Substitution Principle for non-methods #2158
Abstract base classes
tests: return_type.md, overloads.md
-
@abstractmethoddecorator - Empty body allowed for abstract methods
-
@abstractmethodwith@overloadvalidation - Emit diagnostic on constructor call to class with abstract methods #1877
- Emit diagnostic on unsound
super()call to abstract method with trivial body #1923 - Emit diagnostic on unsound call to abstract
@classmethodor@staticmethodwith trivial body, when accessed on the class object itself #1927 - Emit diagnostic for unimplemented abstract method on @final class #2525
__slots__
tests: instance_layout_conflict.md
-
__slots__(string or tuple of strings) -
__slots__(list, dict, set literals) - Attribute resolution from
__slots__support__slots__#1268 - Diagnostic: access outside
__slots__support__slots__#1268 - Diagnostic: class variable shadowing
__slots__name support__slots__#1268 -
__dict__/__weakref__presence validation support__slots__#1268 - Diagnostic: non-empty
__slots__on builtin subclasses support__slots__#1268
Special library features
Standard library:
-
@cached_propertySupportcached_property#1446 -
functools.partialSupport functools.partial #1536 -
functools.total_orderingAdd support forfunctools.total_ordering#1202
Third-party library support (currently not decided how far we want to go here):