Python type hints (type hints)

Python is a dynamic language, variables do not need to be declared before use, and can point to any type of object; on the one hand, it brings convenience to developers, on the other hand, it brings confusion to IDE and code readers. In unknown cases, the IDE cannot give completion prompts and syntax checks


Python supports "type hints" (PEP484) from version 3.5, allowing developers to declare the type of variables

The biggest advantage of type hints is that the IDE can provide completion hints for the corresponding types

  • no type hints

VSCode does not know the type of the parameter and cannot give a completion prompt

  • when there are type hints

VSCode knows that it is a string type, and can list all the methods of the string


Use type hints

The type hint only serves as a hint, and has no effect on the running of the code. The actual type of the variable can be different from the type hint

Type hints include: variable types, parameter types in functions and return value types

  1. declare variable type
sep: str
sep = '-'
age: int = 35
ok: bool = True
pi: float = 3.14159

A variable can declare its type first and then assign a value, or it can declare its type and assign a value at the same time

  1. Declare the parameter and return type of the function

The Python interpreter parses the function's type hints and updates the __annotations__ attribute of the function object

def get_name(f_name: str, l_name: str, sep: str = '-') -> str:
    name = f_name.title() + sep + l_name.title()
    return name


class Cat:

    def __init__(self, name):
        self.name = name

    def do(self, content: str) -> str:
        return f"{
      
      self.name} do {
      
      content}"


print("get_name type-hints:", get_name.__annotations__)
print("Cat.do type-hints:", Cat.do.__annotations__)

For parameters with default values, put the default value after the type hint

output:

get_name type-hints: {'f_name': <class 'str'>, 'l_name': <class 'str'>, 'sep': <class 'str'>, 'return': <class 'str'>}
Cat.do type-hints: {'content': <class 'str'>, 'return': <class 'str'>}

available types

In addition to using the type itself, type hints can also use the string of the type

def show(name: 'str', age: 'int') -> 'None':
    print("name:", name)
    print("age :", age)
container type

In addition to the basic type, the container type can also specify the type of sub-elements, so that when sub-elements are used, the IDE can also provide code completion

2023-04-02_15-38.png

from typing import Tuple


Vector2D = Tuple[int, int]


def show(line: list[int], dots: Vector2D, info: dict[str, str]):
    print('line:', line)
    print('dots:', dots)
    print('info:', info)


show([1], (2, 3), {
    
    'name': 'Hoss'})

There are two ways to specify the type of child elements in a container:

  1. Use built-in container types directly

For example list[int]and dict[str, str], only available for Python 3.9+

  1. With the help of the standard librarytyping

For example Tuple[int, int], the usage is the same as above, just replaced by the alias of the corresponding type

Of course, you can also assign a custom container type to a variable, which is used for type hints

Guess you like

Origin blog.csdn.net/jiang_huixin/article/details/129914221