How to Use Type Hint to improve Python program development efficiency and hintpython

Source: Internet
Author: User

How to Use Type Hint to improve Python program development efficiency and hintpython

Introduction

Type Hint (or PEP-484) provides a Type tagging standard for Python programs.

Why Type Hint? For dynamic languages, it is often the case that after you write a piece of code, you may forget what the prototype of this method looks like in the next time, you do not know what type of parameters should be passed in, so you often need to read the code to define what each type is. Or when you use a third-party library that is not completely a document, you don't know how to use it.

Now, with the help of Type Hint, you can implement:

1. Implement type check to prevent non-conforming types during running.

2. As an additional Property of the document, it is convenient for developers to pass in the parameter type when calling.

3. Improve the check mechanism of the IDE, and provide prompt and type check results faster during smart prompts.

In this process, you need to usePython 3.5 +New ModuleTyping.It is worth noting thatThis change does not affect the program running, just to facilitate the implementation of the type checker.

Type Hint Type checker

Currently, for example, PyCharm of JetBrains already supports the Type Hint syntax check function. If you use this IDE, You can implement it through the IDE function. If you use the SublimeText editor like me, the third-party tool mypy can help you. The version 2.0 to be released by AnacondaST3 also has built-in support for the mypy function. For details about the progress, refer to this issue. Some other Python tools (such as the code prompt tool jedi 0.10 +) also support the Type Hint function.

Start with a simple example.

Starting from a simple example, we start with a simple program. The runtime environment is Python 3.5.2 and the mypy tool is used for check.

First passpip install mypy-langCommand to install the mypy tool. Note that mypy-lang is used because the name of mypy in pypi has been occupied.

Next, use mypy to check the following file

# fib.pyfrom typing import Iteratordef fib(n: int) -> Iterator[int]:  a, b = 0, 1  while a < n:    yield a    a, b = b, a + bi = fib(3.2)print(next(i))print(next(i))

Execute commands in the command linemypy fib.pyTo obtain the returned results:

➜ mypy fib.pyfib.py:11: error: Argument 1 to "fib" has incompatible type "float"; expected "int"

However, in the actual application process, this function can run normally in Python:

➜ mypy python fib.py01

As you can see, the mypy tool prompts that there is a Type Mismatch problem in our code, but if we do not check it, the Code may execute unpredictable results.

In this example, we use two types: one is the basic Python data type, such as str and int, which can be directly used; the Iterator introduced in typing is used to represent the Iterator type. It is worth noting that some types in typing are also added at any time. Generally, the demo version prevails.

From simple to complex, what should I do with type combinations?

In fact, some more complex parameter types, such as list type and tuple type, may be passed during use. How can we declare such data? Let's first look at an example:

def foo(strings, string_list, count, total):

The parameters of this function can be viewed literally as str. The elements are the list type and two Integer Parameters of str. Let's assume that a returned value is((int, int), str),This type check can be defined as follows:

from typing import List, TupleResult = Tuple[Tuple[int, int], str]def foo(strings: str, lines: List[str], line_number: int, total_lines: int) -> Result:

Other types of prompts and coroutine support can be viewed in the official typing module documentation.

Idle talk about production

We are also testing the specific use of some mypy tools in the production environment, but we also found some problems, for example, the dynamic language features of Python bring some trouble to type annotation. In addition, the type transformation caused by variable Reuse may prompt the adoption of new variables. This is relatively costly for an existing online project. We will also adopt this method in some new projects in the future. In addition, mypy is a relatively new project with some bugs. In addition, some non-type error prompts of mypy are actually very vague, resulting in many errors that sometimes require manual troubleshooting.

In any case, even if there are some defects in mypy, it is still a very promising tool in the future. understanding and applying it in advance can effectively improve the robustness of the program. The above is all about how to use Type Hint to improve Python program development efficiency. I hope this article will help you with python.

Related Article

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.