Preface and environmental assumptions

Pycharm 2017 earlier versions of Pycharm do not support Type hints, so newer versions are assumed here.

Python 3.5 is now becoming more and more mainstream in the Python community, with several heavyweight libraries/frameworks no longer supporting Python 2. Since 3.5 is an important release (if it’s a new project, it’s more likely to go straight to 3.5/3.6), this article uses 3.5.

Static typing is important because I’m not a professional, so I’ll call it that. Since Python is a dynamic language, Type Hint is not the same thing as static typing like C++/Java. It is just an IDE Hint. The good news is that most people use an IDE to program these days, so Type hints are still useful.

In short, if you compare Java/C++ to a rocket cannon, then Type Hint is a lighter. Left and right, lighter is better than “drill wood for fire” :).

Possible demand

For type annotation, we may have the following requirements.

One is the input parameter. According to the parameter type, it can be divided into the following categories:

  1. Basic built-in types such as STR, int, list
  2. Complex types resulting from the combination of basic types, such as list[int], dict[STR, int]
  3. User defined class, such as Person, Animal
  4. Function arguments, callable, such as callback arguments: (value: STR, index: int) => STR

The second is the output parameter (return value). Basically and the classification of the parameters are consistent, not to repeat.

Let’s look at how we can implement the requirements listed above in 2 and 3, respectively.

Python 2: Doc String

Pycharm has quite complete support for this, which is basically sufficient, the only drawback is that it is tedious.

The following is an example:

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_name(self):
        return self._name

    def get_age(self):
        return self._age


class Py2TypehintTester:
    def test1(self, a, b, c):
        """Type A: STR :param a: :type B: STR :param B: :type C: list :param C: :rtype: list :return:"""

        return [a, b, c]

    def test2(self, a, b, c):
        """Type a: list[STR] :param a: :type b: list[int] :param b: :type c: dict[str, int] :param c: :rtype: dict[str, str] :return: """

        for item in a:
            item.upper()

    def test3(self, p):
        """The third need is also easy to satisfy. Type p: Person :param p: :return: "Person :param p: :return:"""

        age = p.get_age()

    def test4(self, callback):
        """Type callback: (STR, int) -> STR :param callback: :return:"""

        s = 's'
        i = 1

        result = callback(s, i)
        print(result)  # can be correctly derived as STR
Copy the code

The advantage of this approach is obvious: there are no dependencies, you just need to follow the rules.

Python 3: Type Hint

This approach is official, and it’s basically simpler and more intuitive than the previous one, and it may take some getting used to.

The following is an example:

import typing  # Need to import this library

# generate a compound type
FloatVector = typing.List[float]
StrList = typing.List[str]
MyT = typing.TypeVar('T')


class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_name(self):
        return self._name

    def get_age(self):
        return self._age


class Py3TypehintTester:
    def test1(self, a: str, b: str, c: str) -> list:
        """Param a: :param B: :param C: :return:"""
        return [a, b, c]

    def test2(self, a: typing.List[str], 
                    b: typing.List[str], 
                    c: typing.Dict[str, int]) -> typing.Dict[str, str]:
        """第二种需求

        比较简单, 需要先了解 typing 这个库

        :param a:
        :param b:
        :param c:
        :return:
        """

        return {
            'str': 'str1'
        }

    def test3(self, p: Person):
        """The third requirement is simple :param p: :return:"""

        print(p.get_age())

    def test4(self, callback: typing.Callable[[str, int], str]):
        """The fourth requirement is a bit more complicated and requires a careful reading of the code, but it doesn't come up very often, so it doesn't really matter :param callback: :return:"""

        s = 's'
        i = 1
        result = callback(s, i)
        print(result)  # can be derived as STR
Copy the code

I practice

if>= 3.5: use the second version, after all, it is much more simple, and there is no cost to learn, more than ten minutes of things are required: IDE version and Python version are requiredelse: Use the first one as a transition, but compatibility is the best, either version of Pycharm will work correctlyCopy the code

The appendix

  • Pycharm type hint document: https://www.jetbrains.com/help/pycharm/type-hinting-in-pycharm.html