python check function and variable type

Python is a popular programming language. It was created by Guido van Rossum and released in 1991.

1. Python syntax compared with other programming languages

  • Python was designed for readability, has some similarities to English, and is influenced by mathematics.
  • Python uses newlines to complete commands, unlike other programming languages ​​that typically use semicolons or parentheses.
  • Python relies on indentation, using spaces to define scope; such as the scope of loops, functions, and classes. Other programming languages ​​often use curly braces for this purpose.

2. Data type checking

2.1 Basic type specification

For example:

def test(a: int, b: str) -> str:
	print(a, b)
	return 12345	# 返回值类型错误,pycharm解释器会警告

if __name__ == '__main__':
	test(12, "wer")
	test('test', "aaa")	# 错误示例,一般pycharm解释器会警告

The function test above specifies that the input parameter a is of type int, and b is of type str, and the return value is of type srt. It can be seen that in the method, we finally returned an int, and pycharm will have a warning at this time; when we call this method, the parameter a we input is a string, and there will be a warning at this time; but it is very important The point is that pycharm only gives a warning, but in fact it will not report an error when running. After all, the essence of python is still a dynamic language.

2.2 Complex type specification

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]
    
# 类型检查,将float类型的集合赋值给vector集合
new_vector = scale(2.0, [1.0, -4.2, 5.4])
from typing import Dict, Tuple, Sequence

ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    pass

# 静态类型检查器将把之前的类型签名视为与这个签名完全等同
def broadcast_message(
        message: str,
        servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
    pass

2.3 Generic specification

from typing import Sequence, TypeVar, Union

T = TypeVar('T')

def first(l: Sequence[T]) -> T:
    return l[0]

T = TypeVar('T')  # 可以是任意类型
A = TypeVar('A', str, bytes)  # 必须是str或bytes类型
A = Union[str, None] # 必须是str或None类型

2.4 Type specification when creating variables

from typing import NamedTuple

class Employee(NamedTuple):
    name: str
    id: int = 3

employee = Employee('Guido')
assert employee.id == 3

3. Python data types

3.1 Built-in data types

type keywords
text type: str
Numeric type: int, float, complex
sequence type: list, tuple, range
Mapping type: dict
collection type: set, frozenset
Boolean type: bool
Binary type: bytes, bytearray, memoryview

3.2 Set data type

example type of data
x = “Hello World” str
x = 29 int
x = 29.5 float
x = 1j complex
x = [“apple”, “banana”, “cherry”] list
x = (“apple”, “banana”, “cherry”) tuple
x = range(6) range
x = {“name” : “Bill”, “age” : 63} dict
x = {“apple”, “banana”, “cherry”} set
x = frozenset({“apple”, “banana”, “cherry”}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

3.3 Set a specific data type

example type of data
x = str(“Hello World”) str
x = int(29) int
x = float(29.5) float
x = complex(1j) complex
x = list((“apple”, “banana”, “cherry”)) list
x = tuple((“apple”, “banana”, “cherry”)) tuple
x = range(6) range
x = dict(name=“Bill”, age=36) dict
x = set((“apple”, “banana”, “cherry”)) set
x = frozenset((“apple”, “banana”, “cherry”)) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

Guess you like

Origin blog.csdn.net/qq_43522889/article/details/130346272