python: enforcing type check on function using decorator

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  def typeassert(*ty_args, **ty_kwargs):
        """
        利用装饰器对函数参数强制性类型检查
        enforcing type check on function using decorator
        :param ty_args:
        :param ty_kwargs:
        :return:
        """
        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
 
    @typeassert(int, z=int)
    def spam(x, y, z=42):
        """
 
        :param y:
        :param z:
        :return:
        """
        print(x, y, z)
 
#https://github.com/yidao620c/python3-cookbook/blob/master/source/c09/p07_enforcing_type_check_on_function_using_decorator.rst

  

posted @   ®Geovin Du Dream Park™  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2010-06-15 asp.net 3.5 csharp 实现事务
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示