First steps
Type system reference
Configuring and running mypy
Miscellaneous
Project Links
This section will help get you started annotating yourclasses. Built-in classes such asint also follow these samerules.
The mypy type checker detects if you are trying to access a missingattribute, which is a very common programming error. For this to workcorrectly, instance and class attributes must be defined orinitialized within the class. Mypy infers the types of attributes:
classA:def__init__(self,x:int)->None:self.x=x# Aha, attribute 'x' of type 'int'a=A(1)a.x=2# OK!a.y=3# Error: "A" has no attribute "y"
This is a bit like each class having an implicitly defined__slots__ attribute. This is only enforced during typechecking and not when your program is running.
You can declare types of variables in the class body explicitly usinga type annotation:
classA:x:list[int]# Declare attribute 'x' of type list[int]a=A()a.x=[1]# OK
As in Python generally, a variable defined in the class body can be usedas a class or an instance variable. (As discussed in the next section, youcan override this with aClassVar annotation.)
Similarly, you can give explicit types to instance variables definedin a method:
classA:def__init__(self)->None:self.x:list[int]=[]deff(self)->None:self.y:Any=0
You can only define an instance variable within a method if you assignto it explicitly usingself:
classA:def__init__(self)->None:self.y=1# Define 'y'a=selfa.x=1# Error: 'x' not defined
The__init__ method is somewhat special – it doesn’t return avalue. This is best expressed as->None. However, since many feelthis is redundant, it is allowed to omit the return type declarationon__init__ methodsif at least one argument is annotated. Forexample, in the following classes__init__ is considered fullyannotated:
classC1:def__init__(self)->None:self.var=42classC2:def__init__(self,arg:int):self.var=arg
However, if__init__ has no annotated arguments and no return typeannotation, it is considered an untyped method:
classC3:def__init__(self):# This body is not type checkedself.var=42+'abc'
You can use aClassVar[t] annotation to explicitly declare that aparticular attribute should not be set on instances:
fromtypingimportClassVarclassA:x:ClassVar[int]=0# Class variable onlyA.x+=1# OKa=A()a.x=1# Error: Cannot assign to class variable "x" via instanceprint(a.x)# OK -- can be read through an instance
It’s not necessary to annotate all class variables usingClassVar. An attribute without theClassVar annotation canstill be used as a class variable. However, mypy won’t prevent it frombeing used as an instance variable, as discussed previously:
classA:x=0# Can be used as a class or instance variableA.x+=1# OKa=A()a.x=1# Also OK
Note thatClassVar is not a class, and you can’t use it withisinstance() orissubclass(). It does not change Pythonruntime behavior – it’s only for type checkers such as mypy (andalso helpful for human readers).
You can also omit the square brackets and the variable type inaClassVar annotation, but this might not do what you’d expect:
classA:y:ClassVar=0# Type implicitly Any!
In this case the type of the attribute will be implicitlyAny.This behavior will change in the future, since it’s surprising.
An explicitClassVar may be particularly handy to distinguishbetween class and instance variables with callable types. For example:
fromcollections.abcimportCallablefromtypingimportClassVarclassA:foo:Callable[[int],None]bar:ClassVar[Callable[[A,int],None]]bad:Callable[[A],None]A().foo(42)# OKA().bar(42)# OKA().bad()# Error: Too few arguments
Note
AClassVar type parameter cannot include type variables:ClassVar[T] andClassVar[list[T]]are both invalid ifT is a type variable (seeDefining generic classesfor more about type variables).
When overriding a statically typed method, mypy checks that theoverride has a compatible signature:
classBase:deff(self,x:int)->None:...classDerived1(Base):deff(self,x:str)->None:# Error: type of 'x' incompatible...classDerived2(Base):deff(self,x:int,y:int)->None:# Error: too many arguments...classDerived3(Base):deff(self,x:int)->None:# OK...classDerived4(Base):deff(self,x:float)->None:# OK: mypy treats int as a subtype of float...classDerived5(Base):deff(self,x:int,y:int=0)->None:# OK: accepts more than the base...# class method
Note
You can also vary return typescovariantly in overriding. Forexample, you could override the return typeIterable[int] with asubtype such aslist[int]. Similarly, you can vary argument typescontravariantly – subclasses can have more general argument types.
In order to ensure that your code remains correct when renaming methods,it can be helpful to explicitly mark a method as overriding a basemethod. This can be done with the@override decorator.@overridecan be imported fromtyping starting with Python 3.12 or fromtyping_extensions for use with older Python versions. If the basemethod is then renamed while the overriding method is not, mypy willshow an error:
fromtypingimportoverrideclassBase:deff(self,x:int)->None:...defg_renamed(self,y:str)->None:...classDerived1(Base):@overridedeff(self,x:int)->None:# OK...@overridedefg(self,y:str)->None:# Error: no corresponding base method found...
Note
Use–enable-error-code explicit-override to requirethat method overrides use the@override decorator. Emit an error if it is missing.
You can also override a statically typed method with a dynamicallytyped one. This allows dynamically typed code to override methodsdefined in library classes without worrying about their typesignatures.
As always, relying on dynamically typed code can be unsafe. There is noruntime enforcement that the method override returns a value that iscompatible with the original return type, since annotations have noeffect at runtime:
classBase:definc(self,x:int)->int:returnx+1classDerived(Base):definc(self,x):# Override, dynamically typedreturn'hello'# Incompatible with 'Base', but no mypy error
Mypy supports Pythonabstract base classes (ABCs). Abstract classeshave at least one abstract method or property that must be implementedby anyconcrete (non-abstract) subclass. You can define abstract baseclasses using theabc.ABCMeta metaclass and the@abc.abstractmethodfunction decorator. Example:
fromabcimportABCMeta,abstractmethodclassAnimal(metaclass=ABCMeta):@abstractmethoddefeat(self,food:str)->None:pass@property@abstractmethoddefcan_walk(self)->bool:passclassCat(Animal):defeat(self,food:str)->None:...# Body omitted@propertydefcan_walk(self)->bool:returnTruex=Animal()# Error: 'Animal' is abstract due to 'eat' and 'can_walk'y=Cat()# OK
Note that mypy performs checking for unimplemented abstract methodseven if you omit theABCMeta metaclass. This can be useful if themetaclass would cause runtime metaclass conflicts.
Since you can’t create instances of ABCs, they are most commonly used intype annotations. For example, this method accepts arbitrary iterablescontaining arbitrary animals (instances of concreteAnimalsubclasses):
deffeed_all(animals:Iterable[Animal],food:str)->None:foranimalinanimals:animal.eat(food)
There is one important peculiarity about how ABCs work in Python –whether a particular class is abstract or not is somewhat implicit.In the example below,Derived is treated as an abstract base classsinceDerived inherits an abstractf method fromBase anddoesn’t explicitly implement it. The definition ofDerivedgenerates no errors from mypy, since it’s a valid ABC:
fromabcimportABCMeta,abstractmethodclassBase(metaclass=ABCMeta):@abstractmethoddeff(self,x:int)->None:passclassDerived(Base):# No error -- Derived is implicitly abstractdefg(self)->None:...
Attempting to create an instance ofDerived will be rejected,however:
d=Derived()# Error: 'Derived' is abstract
Note
It’s a common error to forget to implement an abstract method.As shown above, the class definition will not generate an errorin this case, but any attempt to construct an instance will beflagged as an error.
Mypy allows you to omit the body for an abstract method, but if you do so,it is unsafe to call such method viasuper(). For example:
fromabcimportabstractmethodclassBase:@abstractmethoddeffoo(self)->int:pass@abstractmethoddefbar(self)->int:return0classSub(Base):deffoo(self)->int:returnsuper().foo()+1# error: Call to abstract method "foo" of "Base"# with trivial body via super() is unsafe@abstractmethoddefbar(self)->int:returnsuper().bar()+1# This is OK however.
A class can inherit any number of classes, both abstract andconcrete. As with normal overrides, a dynamically typed method canoverride or implement a statically typed method defined in any baseclass, including an abstract method defined in an abstract base class.
You can implement an abstract property using either a normalproperty or an instance variable.
When a class has explicitly defined__slots__,mypy will check that all attributes assigned to are members of__slots__:
classAlbum:__slots__=('name','year')def__init__(self,name:str,year:int)->None:self.name=nameself.year=year# Error: Trying to assign name "released" that is not in "__slots__" of type "Album"self.released=Truemy_album=Album('Songs about Python',2021)
Mypy will only check attribute assignments against__slots__ whenthe following conditions hold:
All base classes (except builtin ones) must have explicit__slots__ defined (this mirrors Python semantics).
__slots__ does not include__dict__. If__slots__includes__dict__, arbitrary attributes can be set, similar towhen__slots__ is not defined (this mirrors Python semantics).
All values in__slots__ must be string literals.