Python Code Intellisense - Type Annotations and Special Comments (Everybody Needs to Know)

A Python programmer who can't write good type annotations and comments is a painful thing for people who use TA's code...

—— Big Boss

1. Code Intellisense

        Presumably most modern integrated development environments (IDEs) have code intellisense!

        IntelliSense means that when we write code, the code editor automatically pops up the part of our code that needs to be completed, and these completed parts are obtained by the code editor through IntelliSense. Most importantly, the code The editor intelligently senses that the completed part is obtained by the type of the variable in the code.

general intellisense

After saying so much, everyone must know what IntelliSense is, but sometimes, the code does not have IntelliSense (as follows)

intellisense failure

When the amount of code is large, the Intellisense of the code is very important. It can help you quickly understand what this variable is and what that variable is, so as to reduce your production BUG!

        Writing a good comment (or type annotation) is not only for the convenience of people who reuse your code in the future, but also for yourself. In fact, "for yourself" is not just for the convenience of yourself to understand the code, but also to make the IDE intelligent When the IDE understands your code, it will provide you with corresponding information (such as code completion and prompts), which is extremely friendly to programmers!

By understanding the following type annotations and special annotations , you will solve almost all intellisense failure problems! 

2. Type label

There are several types of Python type annotations, and I will give some of the ones I know below

Type annotations for function parameters 

【Simple operation】

def function(num: int, string: str):
    pass

In the above code, the function parameter is followed by a colon and a class name , representing the data type of the parameter. The class name can be a built-in class, such as str, int, float, etc., or a class defined by yourself. It can also be a class in a module or library, such as tkinter.Tk

The num parameter is of type int, and the string parameter is of type str. These type annotations can be seen not only where the function is defined, but also through the IDE’s intellisense when calling the function (as follows)

Type annotations for function parameters

After this type is marked, it does not force the parameter to use this type, it just serves as a reminder, which is equivalent to a comment. At the same time, the IDE will give corresponding code hints through the IntelliSense type mark

code hints

【Advanced operation】

import typing

def function(num: int,
             lis: list[int],
             key: typing.Literal[4, 5, 6],
             string: str | None = '123'):
    pass

In the code above:

list[int] means that the data type of the lis parameter is a list type containing integer data

typing is an official built-in module, specially used for type annotation, typing.Literal[4, 5, 6] indicates that the expected value of the parameter key can only be 4, 5 or 6, that is to say, the key parameter received by this function, It only expects it to be one of the three values ​​4, 5 or 6

str | None means that the data type of the string parameter can be str or None type. Let me explain here that the operation of using "|" in the type annotation to represent or was only added in Python3.10. In previous versions, this usage was only available in pyi files (Python stub files)

In the following code hints, we can see the effect of the type annotation similar to the above

advanced operation

By the way, the default value of the meaning of the ellipsis (three consecutive decimal points) (generally used in pyi stub files)

Type annotations for function return values

def pow(m: int, n: int) -> int:
    return m**n

The type annotation of the function return value is similar to the parameter type annotation mentioned above, except that the type marked here is only the data type of the return value of the function. Similarly, it only serves as a reminder and has no mandatory effect

This annotation also has advanced usage, which is exactly the same as the above, so I won’t go into details here

By the way, list[int, int, int] represents a list type containing three integer data

Variable Type Annotation

Rumor has it that there is a way of writing that falls from the sky, I wonder if you have seen it

key: int
key = 3

"""
或者这样写:
key: int = 3
"""

print(key) # 输出3

Adding a colon and a class name after the variable name is also a kind of type annotation, but it is not a function parameter, but a general variable, and the usage is the same as above

So, what is the use of this type annotation? If you directly assign a value to the variable as a list, won't the IDE recognize it?

This is really useless for general variables, but you can see the following operation

Variable Type Annotation

In the above situation, when the variable is not type marked in advance, it is extremely troublesome to write the code later because there is no prompt from the IDE

There is another method of variable type annotation, which will be mentioned later in Special Notes

3. Special notes

A seemingly ordinary comment actually has a special effect, just like the special comment in C# (three slashes "///"), Python also has its special comment

【Three quotation mark notes】

Presumably a qualified Python programmer knows the special function of triple quote comments.

It's not just an ordinary comment, it can wrap lines (you know it), it's written under functions and classes to indicate help documents, etc... I won't go into details here

[special # comments]

It can only comment on a single line... Does it have other features besides that? ? ? right! Other features!

When a # comment is written in such a format, it has the same effect as a type annotation! ! !

key = [] # type: list[float]

# Write type after the comment, add a colon, and then add the data type, it becomes a type annotation! ! !

special # comments

Is it that most people don't know this feature?

4. Special types

There are some special data types, some of which are not built-in but are considered built-in, but it is not easy for you to find them, such as iterator type, generator type, function type (a function in Python is actually an object, and also has a type), etc. Wait, a table is given below to facilitate the labeling of types

type name type of data Citation
function function

function

types.FunctionType

method method

types.MethodType

iterator Iterator

typing.Iterator

collections.abc.Iterator

Builder Generator

typing.Generator

collections.abc.Generator

sequence Sequence

typing.Sequence

collections.abc.Sequence


[After reading so much, do you feel that your knowledge has increased again? So, what about your likes? 】 

Guess you like

Origin blog.csdn.net/weixin_62651706/article/details/126936985