Python 函数注解 随性笔记)

本文探讨了Python函数定义的弊端,如动态类型导致的问题,以及如何通过增加文档字符串和函数注解来改善。Python 3.5引入的函数注解允许对参数和返回值进行类型声明,但不强制类型检查,主要用作辅助说明和代码分析。3.6版本引入了变量注解。文章还提出了函数参数检查的思路,建议使用装饰器实现。
摘要由CSDN通过智能技术生成

1、Python 函数定义的弊端

  • Python 是动态语言,变量随时可以被赋值,且能赋值为不同的类型

  • Python 不是静态编译语言,变量类型实在运行期决定的

  • 动态语言很灵活,但是这种特性也是弊端

    • 难发现:由于不做任何类型检查,知道运行期问题才显现出来,或者线上运行时才能暴露出问题
    • 难使用:函数的使用者看到函数的时候,并不知道你的函数设计,并不知道应该传入什么类型的数据
  • 请看以下例子:

    def add(x, y):
        return x + y
    
    print(add(3, 5))
    print(add('hello', 'world'))
    print(add('hello', 5))
    
    8
    helloworld
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-238-6e69a92ee60e> in <module>
          4 print(add(3, 5))
          5 print(add('hello', 'world'))
    ----> 6 print(add('hello', 5))
    
    <ipython-input-238-6e69a92ee60e> in add(x, y)
          1 def add(x, y):
    ----> 2     return x + y
          3 
          4 print(add(3, 5))
          5 print(add('hello', 'world'))
    
    TypeError: can only concatenate str (not "int") to str
    

2、函数定义的弊端的解决方法

如何解决这种动态语言定义的弊端呢?有以下两种方法。

2.1 增加文档 Documentation String

  • 这只是一个惯例,不是强制标准,不能要求程序员一定要为函数提供说明文档

  • 函数定义更新了,文档未必同步更新

    def add(x, y):
        """
        :param x:int
        :param y: int
        :return: int
        """
        return x + y
    
    print(help(add))
    
    Help on function add in module __main__:
    
    add(x, y)
        :param x:int
        :param y: int
        :return: int
    
    None
    

2.1 增加函数注解 Function Annotations

  • Python 3.5 引入
  • 对函数的参数进行类型注解
  • 对函数的返回值进行类型注解
  • 只对函数参数做一个辅助的说明,并不对函数参数进行类型检查
  • 提供给第三方工具做代码分析,发现隐藏bug
  • 函数注解的信息,保存在 __annotations__ 属性中
  • Python 3.6 引入 变量注解。注意它也只是对变量的说明,非强制 i:int = 5
  • 类型不一样时,解释器会着色,但是不影响执行

在这里插入图片描述

def add(x:int, y:int) -> int:
    """
    :param x:int
    :param y: int
    :return: int
    """
    return x + y

print(help(add))
print(add.__annotations__)
Help on function add in module __main__:

add(x: int, y: int) -> int
    :param x:int
    :param y: int
    :return: int

None
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}

Process finished with exit code 0

3、业务应用

如果对函数参数类型进行检查,有如下思路:

  • 函数参数的检查,一定是在函数外
  • 函数应该作为参数,传入到检查函数中
  • 检查函数拿到函数传入的实际参数,与形参声明对比
  • __annotations__ 属性是一个字典,其中包括返回值类型的声明。
  • 假设要做位置参数的判断,无法和字典中的声明对应,需要使用 inspect 模块
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值