本网站可以通过分类标签帮助你快速筛选出你想看的文章,记住地址:www.Facec.cc

python新特性-变量规定类型-海象运算符-函数规定参数类型

变量规定类型

from typing import List, Set, Dict, Tuple

# 字符数组
course: List[str] = ['django','abc','ccc']

# 字典
user_info: Dict[str, float] = {"height":180.0 }


# 普通变量
age: int = 18
name: str = "wdf"
sex: bool = True
weight: float = 75
x:bytes = b"bytes"


# !!!类型声明, 不会影响使用, 编辑器会产生提示

海象运算符

# python

course_list = ["语文", "数学", "英语"]
if (course_size := len(course_list)) >=3:
	print(course_size) # 3

函数规定参数类型

# python

def add1(a: int, b: int) -> int:
    return a+b

def add2(a: int, b: int) -> None:
    return None

print(add1.__annotations__) # {'a': <class 'int'>, 'b': <class 'int'>, 'c': <class 'int'>}



# 百度出来的一个校验
def para_check(func):
    import collections
    import functools
    import inspect
    """
    函数参数检查装饰器,需要配合函数注解表达式(Function Annotations)使用
    """
    msg = 'Argument {argument} must be {expected!r},but got {got!r}, value {value!r}'

    # 获取函数定义的参数
    sig = inspect.signature(func)
    parameters = sig.parameters  # 参数有序字典
    arg_keys = tuple(parameters.keys())  # 参数名称

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        CheckItem = collections.namedtuple('CheckItem', ('anno', 'arg_name', 'value'))
        check_list = []

        # collect args   *args 传入的参数以及对应的函数参数注解
        for i, value in enumerate(args):
            arg_name = arg_keys[i]
            anno = parameters[arg_name].annotation
            check_list.append(CheckItem(anno, arg_name, value))

        # collect kwargs  **kwargs 传入的参数以及对应的函数参数注解
        for arg_name, value in kwargs.items():
            anno = parameters[arg_name].annotation
            check_list.append(CheckItem(anno, arg_name, value))

        # check type
        for item in check_list:
            if not isinstance(item.value, item.anno):
                error = msg.format(expected=item.anno, argument=item.arg_name,
                                   got=type(item.value), value=item.value)
                raise TypeError(error)

        return func(*args, **kwargs)

    return wrapper




@para_check
def abc(x: int, y: int) -> int:
    return "x + y"


# python  

评论