为什么Python的类型标注没有对类型进行检查?
尝试了一下Python的类型标注(Type Hinting),但是发现Python并没有帮我检查类型。
from typing import *L : List[Tuple[int, str]] = {x:x+10 for x in range(10)}
print(type(L), L)
L应该被标记为整型与字符串元组的列表,但它接受了字典
<class 'dict'> {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19}def foo1(a : str, b : float) -> None: print(type(a), type(b))
foo1([1,2,3,4], 20)
foo1应该接受字符串和浮点数作为参数,但它接受了列表和整型,也没有进行隐式类型转换
<class 'list'> <class 'int'>def foo2(s : str, l : List[int]) -> Set[str]: return str([str(x) + s for x in l])
print(type(foo2('#', list(range(10)))))
foo2 应该返回一个字符串集合,但它接受了字符串
<class 'str'>def foo3(a : int) -> int: return a/3.678
print(type(foo3(10)), foo3(10))
同理,foo3返回了浮点数
<class 'float'> 2.718868950516585更复杂的类型标注我还没有尝试,但标注之后既没有报错也没有提示我觉得有点奇怪,难道typing只是给开发者当提示的吗?
回答:
贴了文档不看的吗?

回答:
给你一个参考的方案吧 自己可以来实现这个功能 我是在python cookbook看到的一个实现 用这个装饰器可以强制类型检查 不然就报错
from functools import wrapsfrom inspect import signature
def typeassert(*ty_args, **ty_kwargs):
    def decorate(func):
        # If in optimized mode, disable type checking
 if not __debug__:
            return func
 # Map function argument names to supplied types
 sig = signature(func)
        bound_types = sig.bind_partial(*ty_args, **ty_kwargs).arguments
        @wraps(func)
        def wrapper(*args, **kwargs):
            bound_values = sig.bind(*args, **kwargs)
            # Enforce type assertions across supplied arguments
            for name, value in bound_values.arguments.items():
                if name in bound_types:
                    if not isinstance(value, bound_types[name]):
                        raise TypeError('Argument {} must be {}'.format(name, bound_types[name])
                                        )
            return func(*args, **kwargs)
        return wrapper
    return decorate
`
以上是 为什么Python的类型标注没有对类型进行检查? 的全部内容, 来源链接: utcz.com/a/160319.html





