"at" sign (@) in Python type hints (suggested by Pylance / Pyright)

Question:

The July 2022 release of the Python extension for Visual Studio Code introduced "Inlay Type Hints", which automatically suggests return types of functions that don’t have an explicit annotation. To enable it, you can set "python.analysis.inlayHints.functionReturnTypes": true to your IDE user settings (Preferences: Open Settings (JSON) command).

While testing this feature, I noticed the following kind of suggestion, inside a class:
enter image description here

… where the highlighted text in yellow is the return type suggested by the Python extension, which is based on Pylance, which itself relies on Pyright.

My question is: what is the @ sign in this suggestion supposed to mean? Is there a PEP that refers to this kind of type annotations (with Self@...) or is that way of type hinting specific to Pyright, differing from the standard convention? Where can I find more information about it?

I’ve found a similar Stackoverflow question here but it did not get any answer.

Asked By: scūriolus

||

Answers:

That @ indicates that Self is a TypeVar, and Self@HereIsMyClassName refers to the Self in the context of the class HereIsMyClassName (it could also be a function). This is not valid Python. (Technically, it is valid, as the @ operator is matrix multiplication, so you are matrix-multiplying Self and HereIsMyClassName. However, that’s not what is meant and really doesn’t make any sense.) Don’t write this in your code, but know that this is how Pylance shows you TypeVars when it shows you type definitions. (Possibly other editors and extensions as well.)

Answered By: pigrammer