Home > Article > Backend Development > Introduction to the typing module in Python (code example)
Python is a weakly typed language. Many times we may not know the function parameter type or return value type, which may lead to some types not specifying methods. The typing module can solve this problem very well.
The addition of this module will not affect the running of the program, and no formal errors will be reported, only reminders.The typing module can only be used in python3.5 or above. Pycharm currently supports typing check
1. The role of the typing module
1. Type Check to prevent parameter and return value type inconsistencies from occurring during runtime.
2. As an attachment to the development document, it is convenient for users to pass in and return parameter types when calling.
2. Commonly used methods of typing module
Look at the example code first:
from typing import List,Tuple,Dict def add(a:int,string:str,f:float,b:bool)->Tuple[List,Tuple,Dict,bool]: list1=list(range(a)) tup=(string,string,string) d={"a":f} bl=b return list1,tup,d,bl if __name__ == '__main__': print(add(5,'mark',183.1,False))
Run result:
([0, 1, 2, 3, 4], ('mark', 'mark', 'mark'), {'a': 183.1}, False)
Explanation:
When passing in parameters, declare the type of the parameter in the form of "parameter name: type";
The return result is passed in "-> Declare the result type in the form of "result type"
. If the parameter type is incorrect when calling, pycharm will remind you, but it will not affect the running of the program.
For lists such as lists, you can also specify something more specific, such as "->List[str]", which specifies that a list is returned and the elements are strings.
Now modify the above code, you can see that the pycharm background turns yellow, which is the error type reminder:
3. Commonly used types of typing
int, long, float: integer, long integer, floating point type
bool,str: Boolean type, string type
List, Tuple, Dict, Set: list, tuple, dictionary, set
Iterable, Iterator: Iterator, iterator type
Generator: Generator type
four , typing supports possible multiple types
Since Python inherently supports polymorphism, there may be multiple elements in the iterator.
Code example:
from typing import List, Tuple, Dict def add(a: int, string: str, f: float, b: bool or str) -> Tuple[List, Tuple, Dict, str or bool]: list1 = list(range(a)) tup = (string, string, string) d = {"a": f} bl = b return list1, tup, d, bl if __name__ == '__main__': print(add(5, 'mark', 183.1, False)) print(add(5, 'mark', 183.1, 'False'))
Running result (no different from not using typing):
([0, 1, 2, 3, 4], ('mark', 'mark', 'mark'), {'a': 183.1}, False) ([0, 1, 2, 3, 4], ('mark', 'mark', 'mark'), {'a': 183.1}, 'False')
The above is the detailed content of Introduction to the typing module in Python (code example). For more information, please follow other related articles on the PHP Chinese website!