Details about type check in Python

Source: Internet
Author: User
Tags apm
Python is a very dynamic language with no type constraints in function definitions. The following article describes the types of checks in Python in detail. For more information, see. Preface

As we all know, Python is a strong type and dynamic type check language. The so-called dynamic type means that we do not need to specify the type of the variable when defining the variable. The Python interpreter will automatically check the variable at runtime.

Compared with a static type language (such as C language), it does not only write a few type declaration characters:

#include 
 
  #include 
  
   #define BUFF 100char* 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__ == '__main__':  main()

The dynamic type frees our thinking from the simulation of computer work to a certain extent, so we can focus more on the problems to be solved: just like the above example, we do not need to worry about the type of parameters accepted by the greeting function and the type of returned values. Instead, we only need to consider the functions that the greeting function needs to implement.

Of course, it does not mean that the dynamic type must be better than the static type. the above example is unfair compared to Python in C language. if it is changed to Go language:

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

The advantage of static types (to some extent, it is also a disadvantage) lies in the establishment of a mandatory protocol (interface) when defining a method. only by following the protocol can we use it correctly. This is helpful for multi-person cooperation, development of third-party libraries, and rapid BUG locating. Another major advantage of static types is that IDE can help prompt interface usage and type check to further improve efficiency. Since there are so many advantages, do you want to learn one from Python? In fact, the PEP 3.5 in Python 484 and the PEP 3.6 in Python 526 are added with the Type Hints syntax, respectively, among them, PEP 484 is mainly about the type declaration syntax of function, method, class parameters and return values, while PEP 526 adds the declaration of variable types:

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

Mypy

Mypy is a static type check tool officially recommended:

python3 -m pip install mypy

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

mypy greeting.py

For ease of use, you can apply it 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

The code with the type annotation added can be executed directly through the Python 3.5 interpreter, but it is completely incompatible with Python 2.x. To use it in Python 2.x, you must first install typing:

pip install typing

Then, you can forcibly add a comment in the form of a single line:

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

For more details about type check in Python, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.