PEP 673 – Self Type | peps.python.org
PEP 673 – Self Type PEP 673 – Self Type Author : Pradeep Kumar Srinivasan <gohanpra at gmail.com>, James Hilton-Balfe <gobot1234yt at gmail.com> Sponsor : Jelle Zijlstra <jelle.zijlstra at gmail.com> Discussions-To : Typing-SIG list Status : Final Type : Standards Track Topic : Typing Created : 10-Nov-2021 Python-Version : 3.11 Post-History : 17-Nov-2021 Resolution : Python-Dev thread Table of Contents Abstract Motivation Usage statistics Specification Use in Method Signatures Use in Classmethod Signatures Use in Parameter Types Use in Attribute Annotations Use in Generic Classes Use in Protocols Valid Locations for Self Runtime behavior Rejected Alternatives Allow the Type Checker to Infer the Return Type Reference Implementations Resources Copyright Important This PEP is a historical document: see Self and typing.Self for up-to-date specs and documentation.
Canonical typing specs are maintained at the typing specs site ; runtime typing behaviour is described in the CPython documentation. × See the typing specification update process for how to propose changes to the typing spec. Abstract This PEP introduces a simple and intuitive way to annotate methods that return an instance of their class. This behaves the same as the TypeVar -based approach specified in PEP 484 but is more concise and easier to follow.
Motivation A common use case is to write a method that returns an instance of the same class, usually by returning self . class Shape : def set_scale ( self , scale : float ): self . scale = scale return self Shape () . set_scale ( 0.5 ) # => should be Shape One way to denote the return type is to specify it as the current class, say, Shape . Using the method makes the type checker infer the type Shape , as expected. class Shape : def set_scale ( self , scale : float ) -> Shape : self . scale = scale return self Shape () . set_scale ( 0.5 ) # => Shape However, when we call set_scale on a subclass of Shape , the type checker still infers the return type to be Shape .
This is problematic in situations such as the one shown below, where the type checker will return an error because we are trying to use attributes or methods not present on the base class. class Circle ( Shape ): def set_radius ( self , r : float ) -> Circle : self . radius = r return self Circle () . set_scale ( 0.5 ) # *Shape*, not Circle Circle () . set_scale ( 0.5 ) . set_radius ( 2.7 ) # => Error: Shape has no attribute set_radius The present workaround for such instances is to define a TypeVar with the base class as the bound and use it as the annotation for the self parameter and the return type: from typing import TypeVar TShape = TypeVar ( "TShape" , bound = "Shape" ) class Shape : def set_scale ( self : TShape , scale : float ) -> TShape : self . scale = scale return self class Circle ( Shape ): def set_radius ( self , radius : float ) -> Circle : self . radius = radius return self Circle () . set_scale ( 0.5 ) . set_radius ( 2.7 ) # => Circle Unfortunately, this is verbose and unintuitive.
Because self is usually not explicitly annotated, the above solution doesn’t immediately come to mind, and even if it does, it is very easy to go wrong by forgetting either the bound on the TypeVar(bound="Shape") or the annotation for self . This difficulty means that users often give up and either use fallback types like Any or just omit the type annotation completely, both of which make the code less safe. We propose a more intuitive and succinct way of expressing the above intention.
We introduce a special form Self that stands for a type variable bound to the encapsulating class. For situations such as the one above, the user simply has to annotate the return type as Self : from typing import Self class Shape : def set_scale ( self , scale : float ) -> Self : self . scale = scale return self class Circle ( Shape ): def set_radius ( self , radius : float ) -> Self : self . radius = radius return self By annotating the return type as Self , we no longer have to declare a TypeVar with an explicit bound on the base class.
The return type Self mirrors the fact that the function returns self and is easier to understand. As in the above example, the type checker will correctly infer the type of Circle().set_scale(0.5) to be Circle , as expected. Usage statistics We analyzed popular open-source projects and found that patterns like the above were used about 40% as often as popular types like dict or Callable . For example, in typeshed alone, such “Self” types are used 523 times, compared to 1286 uses of dict and 1314 uses of Callable as of October 2021 .
This suggests that a Self type will be used quite often and users will benefit a lot from the simpler approach above. Users of Python types have also frequently requested this feature, both on the proposal doc and on GitHub . Specification Use in Method Signatures Self used in the signature of a method is treated as if it were a TypeVar bound to the class. from typing import Self class Shape : def set_scale ( self , scale : float ) -> Self : self . scale = scale return self is treated equivalently to: from typing import TypeVar SelfShape = TypeVar ( "SelfShape" , bound = "Shape" ) class Shape : def set_scale ( self : SelfShape , scale : float ) -> SelfShape : self . scale = scale return self This works the same for a subclass too: class Circle ( Shape ): def set_radius ( self , radius : float ) -> Self : self . radius = radius return self which is treated equivalently to: SelfCircle = TypeVar ( "SelfCircle" , bound = "Circle" ) class Circle ( Shape ): def set_radius ( self : SelfCircle , radius : float ) -> SelfCircle : self . radius = radius return self One implementation strategy is to simply desugar the former to the latter in a preprocessing step.
If a method uses Self in its signature, the type of self within a method will be Self . In other cases, the type of self will remain the enclosing class. Use in Classmethod Signatures The Self type annotation is also useful for classmethods that return an instance of the class that they operate on. For example, from_config in the following snippet builds a Shape object from a given config . class Shape : def __init__ ( self , scale : float ) -> None : ... @classmethod def from_config ( cls , config : dict [ str , float ]) -> Shape : return cls ( config [ "scale" ]) However, this means that Circle.from_config(...) is inferred to return a value of type Shape , when in fact it should be Circle : class Circle ( Shape ): def circumference ( self ) -> float : ... shape = Shape . from_config ({ "scale" : 7.0 }) # => Shape circle = Circle . from_config ({ "scale" : 7.0 }) # => *Shape*, not Circle circle . circumference () # Error: `Shape` has no attribute `circumference` The current workaround for this is unintuitive and error-prone: Self = TypeVar ( "Self" , bound = "Shape" ) class Shape : @classmethod def from_config ( cls : type [ Self ], config : dict [ str , float ] ) -> Self : return cls ( config [ "scale" ]) We propose using Self directly: from typing import Self class Shape : @classmethod def from_config ( cls , config : dict [ str , float ]) -> Self : return cls ( config [ "scale" ]) This avoids the complicated cls: type[Self] annotation and the TypeVar declaration with a bound .
Once again, the latter code behaves equivalently to the former code. Use in Parameter Types Another use for Self is to annotate parameters that expect instances of the current class: Self = TypeVar ( "Self" , bound = "Shape" ) class Shape : def difference ( self : Self , other : Self ) -> float : ... def apply ( self : Self , f : Callable [[ Self ], None ]) -> None : ... We propose using Self directly to achieve the same behavior: from typing import Self class Shape : def difference ( self , other : Self ) -> float : ... def apply ( self , f : Callable [[ Self ], None ]) -> None : ...
Note that specifying self: Self is harmless, so some users may find it more readable to write the above as: class Shape : d
The rest of this page is on the live site.