Home  >  Article  >  Backend Development  >  A detailed introduction to type checking in Python

A detailed introduction to type checking in Python

高洛峰
高洛峰Original
2017-02-20 10:21:241593browse

Preface

Everyone knows that Python is a strongly typed, dynamic type checking language. The so-called dynamic type means that when defining a variable, we do not need to specify the type of the variable. The Python interpreter will automatically check it at runtime.

Compared with statically typed languages ​​(such as C language), this is not just a few less type declaration characters:

#include <stdlib.h>
#include <stdio.h>

#define BUFF 100

char* greeting(char* name){ 
 char* msg = (char *) malloc(sizeof(char) * BUFF);
 sprintf(msg, "Hello, %s!", name);
 return msg;
}

int main(){ 
 printf("Greeting: <%s>\n", greeting("C99"));
 return 0;
}

def greeting(name): 
 return "Hello, {}!".format(name)
def main(): 
 print("Greeting: <%s>" % greeting("Python35"))
if __name__ == &#39;__main__&#39;: 
 main()

Dynamic typing liberates our thinking from the simulation of computer work to a certain extent, and can focus more energy on the problems that need to be solved: like the above For example, we don't need to worry about the types of parameters accepted by the greeting function and the type of the return value, but only need to consider the functions that the greeting function needs to implement.

Of course, this does not mean that dynamic types are necessarily better than static types. It is unfair to compare the above example with C language and Python. If you switch to Go language:

package main

import "fmt"

func greeting(name string) string { 
 return fmt.Sprintf("Hello, %s", name)
}
func main() { 
 fmt.Printf("Greeting: <%s>", greeting("Go"))
}

The advantage (and to some extent disadvantage) of static typing is that a mandatory protocol (interface) is formulated when defining a method, and only by following the protocol can it be used correctly. This is very helpful for multi-person cooperation, developing third-party libraries, quickly locating bugs, etc. Another major advantage of static typing is that it allows the IDE to help prompt interface usage and type checking, further improving efficiency. Since there are so many advantages, should you also learn Python? In fact, PEP 484 in Python 3.5 and PEP 526 in Python 3.6 respectively added the syntax of type hints (Type Hints). PEP 484 is mainly about the type declaration syntax of parameters and return values ​​of functions, methods, classes, and PEP 526 adds Declaration of variable type:

def greeting(name: str) -> str: 
 return "Hello, {}!".format(name)

Mypy

Mypy is an officially recommended static type check Tools:

python3 -m pip install mypy

You can use the mypy command to directly check the Python program:

mypy greeting.py

For It is easy to use and can be applied to the IDE. Taking Atom as an example, you can install the plug-in linter-mypy:

python3 -m pip install typed-ast 
apm install linter 
apm install linter-mypy

A detailed introduction to type checking in Python

The common types supported by Mypy are shown in the following table (from official documentation):

A detailed introduction to type checking in Python

Among them, List/Dict/Iterable/Sequence/Any comes from the standard library typing. The Sequence and Iterable here correspond to collections.abc.Sequence and collections.abc.Iterable respectively. To simply distinguish, Sequence can be indexed by numerical subscript, while Iterable can represent a generator. :

A detailed introduction to type checking in Python

Python 2.x

Code with added type annotations can be executed directly through the Python 3.5 interpreter, but It is completely incompatible with Python 2.x. If you want to use it in Python 2.x, you first need to install the typing:

pip install typing

and then you can force it to be added in the form of a single-line comment:

def send_email(address, # type: Union[str, List[str]] 
  sender, # type: str
  cc,  # type: Optional[List[str]]
  bcc,  # type: Optional[List[str]]
  subject=&#39;&#39;,
  body=None # type: List[str]
  ):
 # type: (...) -> bool
 """Send an email message. Return True if successful."""
 pass

For more detailed introduction to type checking in Python and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn