{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/self-type/",
  "description": "Use Python's Self type from PEP 673 to annotate methods returning class instances, eliminating complex forward references and TypeVars.",
  "path": "/python/self-type/",
  "publishedAt": "2022-02-28T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python",
    "Typing"
  ],
  "textContent": "[PEP-673] introduces the Self type and it's coming to Python 3.11. However, you can\nalready use that now via the [typing_extensions] module.\n\nThe Self type makes annotating methods that return the instances of the corresponding\nclasses trivial. Before this, you'd have to do some mental gymnastics to statically type\nsituations as follows:\n\nThe class Animal has a from_description class method that acts as an additional\nconstructor. It takes a description string, and then builds and returns an instance of the\nsame class. The return type of the method is annotated as Animal here. However, doing this\nmakes the child class Dog conflate its identity with the Animal class. If you execute\nthe snippet, it won't raise any runtime error. Also, Mypy will complain about the type:\n\nTo fix this, we'll have to make sure that the return type of the from_description class\nmethod doesn't confuse the type checker. This is one way to do this:\n\nIn the above snippet, first I had to declare a TypeVar and bind that to the Animal\nclass. Then I had to explicitly type the cls variable in the from_description method.\nThis time, the type checker will be happy. While this isn't a lot of work, it surely goes\nagainst the community convention. Usually, we don't explicitly type the self, cls\nvariables and instead, let the type checker figure out their types. Also, subjectively, this\nsticks out like a sore thumb.\n\nPEP-673 allows us to solve the issue elegantly:\n\nIf you run Mypy against the second snippet, it won't complain.\n\nTyping instance methods that return self\n\nTake a look at this:\n\nThe increment and decrement method of the Counter class return the instance of the\nsame class after performing the operations on the start value. This is a perfect case\nwhere the Self type can be useful.\n\nTyping __new__ methods\n\nYou can also type the __new__ method easily:\n\nThe __new__ method in the Config class validates the var before constructing an\ninstance of the class. The Self type makes it easy to annotate the method.\n\nFurther reading\n\n- [Tweet by Raymond Hettinger]\n\n\n\n\n[pep-673]:\n    https://www.python.org/dev/peps/pep-0673/\n\n[typing_extensions]:\n    https://typing.readthedocs.io/\n\n[tweet by raymond hettinger]:\n    https://twitter.com/raymondh/status/1491187805636407298",
  "title": "Self type in Python"
}