大蟒蛇python教程共享Python Type Hints 学习之从入门到实践

python 想必大家都已经很熟悉了,甚至关于它有用或者无用的论点大家可能也已经看腻了。但是无论如何,它作为一个广受关注的语言还是有它独到之处的,今天我们就再展开聊聊 python。

python 是一门动态强类型语言

《流畅的 python》一书中提到,如果一门语言很少隐式转换类型,说明它是强类型语言,例如 java、c++ 和 python 就是强类型语言。

Python Type Hints 学习之从入门到实践

python 的强类型体现

同时如果一门语言经常隐式转换类型,说明它是弱类型语言,php、javascript 和 perl 是弱类型语言。

Python Type Hints 学习之从入门到实践

动态弱类型语言:javascript

当然上面这种简单的示例对比,并不能确切的说 python 是一门强类型语言,因为 java 同样支持 integer 和 string 相加操作,且 java 是强类型语言。因此《流畅的 python》一书中还有关于静态类型和动态类型的定义:在编译时检查类型的语言是静态类型语言,在运行时检查类型的语言是动态类型语言。静态语言需要声明类型(有些现代语言使用类型推导避免部分类型声明)。

Python Type Hints 学习之从入门到实践

综上所述,关于 python 是动态强类型语言是比较显而易见没什么争议的。

type hints 初探

python 在 pep 484(python enhancement proposals,python 增强建议书)[https://www.python.org/dev/peps/pep-0484/]中提出了 type hints(类型注解)。进一步强化了 python 是一门强类型语言的特性,它在 python3.5 中第一次被引入。使用 type hints 可以让我们编写出带有类型的 python 代码,看起来更加符合强类型语言风格。

这里定义了两个 greeting 函数:

普通的写法如下:

  name = "world"    def greeting(name):      return "hello " + name    greeting(name)  

加入了 type hints 的写法如下:

  name: str = "world"    def greeting(name: str) -> str:      return "hello " + name    greeting(name)  

以 pycharm 为例,在编写代码的过程中 ide 会根据函数的类型标注,对传递给函数的参数进行类型检查。如果发现实参类型与函数的形参类型标注不符就会有如下提示:

Python Type Hints 学习之从入门到实践

常见数据结构的 type hints 写法

上面通过一个 greeting 函数展示了 type hints 的用法,接下来我们就 python 常见数据结构的 type hints 写法进行更加深入的学习。

默认参数

python 函数支持默认参数,以下是默认参数的 type hints 写法,只需要将类型写到变量和默认参数之间即可。

  def greeting(name: str = "world") -> str:      return "hello " + name    greeting()  

自定义类型

对于自定义类型,type hints 同样能够很好的支持。它的写法跟 python 内置类型并无区别。

  class student(object):      def __init__(self, name, age):          self.name = name          self.age = age      def student_to_string(s: student) -> str:      return f"student name: {s.name}, age: {s.age}."    student_to_string(student("tim", 18))  

当类型标注为自定义类型时,ide 也能够对类型进行检查。

Python Type Hints 学习之从入门到实践

容器类型

当我们要给内置容器类型添加类型标注时,由于类型注解运算符 [] 在 python 中代表切片操作,因此会引发语法错误。所以不能直接使用内置容器类型当作注解,需要从 typing 模块中导入对应的容器类型注解(通常为内置类型的首字母大写形式)。

  from typing import list, tuple, dict    l: list[int] = [1, 2, 3]    t: tuple[str, ...] = ("a", "b")    d: dict[str, int] = {      "a": 1,      "b": 2,  }  

不过 pep 585[https://www.python.org/dev/peps/pep-0585/]的出现解决了这个问题,我们可以直接使用 python 的内置类型,而不会出现语法错误。

  l: list[int] = [1, 2, 3]    t: tuple[str, ...] = ("a", "b")    d: dict[str, int] = {      "a": 1,      "b": 2,  }  

类型别名

有些复杂的嵌套类型写起来很长,如果出现重复,就会很痛苦,代码也会不够整洁。

  config: list[tuple[str, int], dict[str, str]] = [      ("127.0.0.1", 8080),      {          "mysql_db": "db",          "mysql_user": "user",          "mysql_pass": "pass",          "mysql_host": "127.0.0.1",          "mysql_port": "3306",      },  ]    def start_server(config: list[tuple[str, int], dict[str, str]]) -> none:      ...    start_server(config)  

此时可以通过给类型起别名的方式来解决,类似变量命名。

  config = list[tuple[str, int], dict[str, str]]      config: config = [      ("127.0.0.1", 8080),      {          "mysql_db": "db",          "mysql_user": "user",          "mysql_pass": "pass",          "mysql_host": "127.0.0.1",          "mysql_port": "3306",      },  ]    def start_server(config: config) -> none:      ...    start_server(config)  

这样代码看起来就舒服多了。

可变参数

python 函数一个非常灵活的地方就是支持可变参数,type hints 同样支持可变参数的类型标注。

  def foo(*args: str, **kwargs: int) -> none:      ...    foo("a", "b", 1, x=2, y="c")  

ide 仍能够检查出来。

Python Type Hints 学习之从入门到实践

泛型

使用动态语言少不了泛型的支持,type hints 针对泛型也提供了多种解决方案。

typevar

使用 typevar 可以接收任意类型。

  from typing import typevar    t = typevar("t")    def foo(*args: t, **kwargs: t) -> none:      ...    foo("a", "b", 1, x=2, y="c")  

union

如果不想使用泛型,只想使用几种指定的类型,那么可以使用 union 来做。比如定义 concat 函数只想接收 str 或 bytes 类型。

  from typing import union    t = union[str, bytes]    def concat(s1: t, s2: t) -> t:      return s1 + s2    concat("hello", "world")  concat(b"hello", b"world")  concat("hello", b"world")  concat(b"hello", "world")    

ide 的检查提示如下图:

Python Type Hints 学习之从入门到实践

typevar 和 union 区别

typevar 不只可以接收泛型,它也可以像 union 一样使用,只需要在实例化时将想要指定的类型范围当作参数依次传进来来即可。跟 union 不同的是,使用 typevar 声明的函数,多参数类型必须相同,而 union 不做限制。

  from typing import typevar    t = typevar("t", str, bytes)    def concat(s1: t, s2: t) -> t:      return s1 + s2    concat("hello", "world")  concat(b"hello", b"world")  concat("hello", b"world")  

以下是使用 typevar 做限定类型时的 ide 提示:

Python Type Hints 学习之从入门到实践

optional

type hints 提供了 optional 来作为 union[x, none] 的简写形式,表示被标注的参数要么为 x 类型,要么为 none,optional[x] 等价于 union[x, none]。

  from typing import optional, union    # none => type(none)  def foo(arg: union[int, none] = none) -> none:      ...      def foo(arg: optional[int] = none) -> none:      ...    

any

any 是一种特殊的类型,可以代表所有类型。未指定返回值与参数类型的函数,都隐式地默认使用 any,所以以下两个 greeting 函数写法等价:

  from typing import optional, union    # none => type(none)  def foo(arg: union[int, none] = none) -> none:      ...      def foo(arg: optional[int] = none) -> none:      ...    

当我们既想使用 type hints 来实现静态类型的写法,也不想失去动态语言特有的灵活性时,即可使用 any。

any 类型值赋给更精确的类型时,不执行类型检查,如下代码 ide 并不会有错误提示:

  from typing import any    a: any = none  a = []  # 动态语言特性  a = 2    s: str = ''  s = a  # any 类型值赋给更精确的类型  

可调用对象(函数、类等)

python 中的任何可调用类型都可以使用 callable 进行标注。如下代码标注中 callable[[int], str],[int] 表示可调用类型的参数列表,str 表示返回值。

  from typing import callable    def int_to_str(i: int) -> str:      return str(i)    def f(fn: callable[[int], str], i: int) -> str:      return fn(i)    f(int_to_str, 2)  

自引用

当我们需要定义树型结构时,往往需要自引用。当执行到 __init__ 方法时 tree 类型还没有生成,所以不能像使用 str 这种内置类型一样直接进行标注,需要采用字符串形式“tree”来对未生成的对象进行引用。

  class tree(object):      def __init__(self, left: "tree" = none, right: "tree" = none):          self.left = left          self.right = right    tree1 = tree(tree(), tree())  

ide 同样能够对自引用类型进行检查。

Python Type Hints 学习之从入门到实践

此形式不仅能够用于自引用,前置引用同样适用。

鸭子类型

python 一个显著的特点是其对鸭子类型的大量应用,type hints 提供了 protocol 来对鸭子类型进行支持。定义类时只需要继承 protocol 就可以声明一个接口类型,当遇到接口类型的注解时,只要接收到的对象实现了接口类型的所有方法,即可通过类型注解的检查,ide 便不会报错。这里的 stream 无需显式继承 interface 类,只需要实现了 close 方法即可。

  from typing import protocol    class interface(protocol):      def close(self) -> none:          ...    # class stream(interface):  class stream:      def close(self) -> none:          ...    def close_resource(r: interface) -> none:      r.close()    f = open("a.txt")  close_resource(f)    s: stream = stream()  close_resource(s)  

由于内置的 open 函数返回的文件对象和 stream 对象都实现了 close 方法,所以能够通过 type hints 的检查,而字符串“s”并没有实现 close 方法,所以 ide 会提示类型错误。

Python Type Hints 学习之从入门到实践

type hints 的其他写法

实际上 type hints 不只有一种写法,python 为了兼容不同人的喜好和老代码的迁移还实现了另外两种写法。

使用注释编写

来看一个 tornado 框架的例子(tornado/web.py)。适用于在已有的项目上做修改,代码已经写好了,后期需要增加类型标注。

Python Type Hints 学习之从入门到实践

使用单独文件编写(.pyi)

可以在源代码相同的目录下新建一个与 .py 同名的 .pyi 文件,ide 同样能够自动做类型检查。这么做的优点是可以对原来的代码不做任何改动,完全解耦。缺点是相当于要同时维护两份代码。

Python Type Hints 学习之从入门到实践

type hints 实践

基本上,日常编码中常用的 type hints 写法都已经介绍给大家了,下面就让我们一起来看看如何在实际编码中中应用 type hints。

dataclass——数据类

dataclass 是一个装饰器,它可以对类进行装饰,用于给类添加魔法方法,例如 __init__() 和 __repr__() 等,它在 pep 557中被定义。

  from dataclasses import dataclass, field      @dataclass  class user(object):      id: int      name: str      friends: list[int] = field(default_factory=list)      data = {      "id": 123,      "name": "tim",  }    user = user(**data)  print(user.id, user.name, user.friends)  # > 123 tim []    

以上使用 dataclass 编写的代码同如下代码等价:

  class user(object):      def __init__(self, id: int, name: str, friends=none):          self.id = id          self.name = name          self.friends = friends or []      data = {      "id": 123,      "name": "tim",  }    user = user(**data)  print(user.id, user.name, user.friends)  # > 123 tim []  

注意:dataclass 并不会对字段类型进行检查。

可以发现,使用 dataclass 来编写类可以减少很多重复的样板代码,语法上也更加清晰。

pydantic

pydantic 是一个基于 python type hints 的第三方库,它提供了数据验证、序列化和文档的功能,是一个非常值得学习借鉴的库。以下是一段使用 pydantic 的示例代码:

  from datetime import datetime  from typing import optional    from pydantic import basemodel      class user(basemodel):      id: int      name = 'john doe'      signup_ts: optional[datetime] = none      friends: list[int] = []      external_data = {      'id': '123',      'signup_ts': '2021-09-02 17:00',      'friends': [1, 2, '3'],  }  user = user(**external_data)    print(user.id)  # > 123  print(repr(user.signup_ts))  # > datetime.datetime(2021, 9, 2, 17, 0)  print(user.friends)  # > [1, 2, 3]  print(user.dict())  """  {      'id': 123,      'signup_ts': datetime.datetime(2021, 9, 2, 17, 0),      'friends': [1, 2, 3],      'name': 'john doe',  }  """  

注意:pydantic 会对字段类型进行强制检查。

pydantic 写法上跟 dataclass 非常类似,但它做了更多的额外工作,还提供了如 .dict() 这样非常方便的方法。

再来看一个 pydantic 进行数据验证的示例,当 user 类接收到的参数不符合预期时,会抛出 validationerror 异常,异常对象提供了 .json() 方法方便查看异常原因。

  from pydantic import validationerror    try:      user(signup_ts='broken', friends=[1, 2, 'not number'])  except validationerror as e:      print(e.json())  """  [    {      "loc": [        "id"      ],      "msg": "field required",      "type": "value_error.missing"    },    {      "loc": [        "signup_ts"      ],      "msg": "invalid datetime format",      "type": "value_error.datetime"    },    {      "loc": [        "friends",        2      ],      "msg": "value is not a valid integer",      "type": "type_error.integer"    }  ]  """  

所有报错信息都保存在一个 list 中,每个字段的报错又保存在嵌套的 dict 中,其中 loc 标识了异常字段和报错位置,msg 为报错提示信息,type 则为报错类型,这样整个报错原因一目了然。

mysqlhandler

mysqlhandler[https://github.com/jianghushinian/python-scripts/blob/main/scripts/mysql_handler_type_hints.py]是我对 pymysql 库的封装,使其支持使用 with 语法调用 execute 方法,并且将查询结果从 tuple 替换成 object,同样也是对 type hints 的应用。

  class mysqlhandler(object):      """mysql handler"""        def __init__(self):          self.conn = pymysql.connect(              host=db_host,              port=db_port,              user=db_user,              password=db_pass,              database=db_name,              charset=db_charset,              client_flag=client.multi_statements,  # execute multi sql statements          )          self.cursor = self.conn.cursor()        def __del__(self):          self.cursor.close()          self.conn.close()        @contextmanager      def execute(self):          try:              yield self.cursor.execute              self.conn.commit()          except exception as e:              self.conn.rollback()              logging.exception(e)        @contextmanager      def executemany(self):          try:              yield self.cursor.executemany              self.conn.commit()          except exception as e:              self.conn.rollback()              logging.exception(e)        def _tuple_to_object(self, data: list[tuple]) -> list[fetchobject]:          obj_list = []          attrs = [desc[0] for desc in self.cursor.description]          for i in data:              obj = fetchobject()              for attr, value in zip(attrs, i):                  setattr(obj, attr, value)              obj_list.append(obj)          return obj_list        def fetchone(self) -> optional[fetchobject]:          result = self.cursor.fetchone()          return self._tuple_to_object([result])[0] if result else none        def fetchmany(self, size: optional[int] = none) -> optional[list[fetchobject]]:          result = self.cursor.fetchmany(size)          return self._tuple_to_object(result) if result else none        def fetchall(self) -> optional[list[fetchobject]]:          result = self.cursor.fetchall()          return self._tuple_to_object(result) if result else none  

运行期类型检查

type hints 之所以叫 hints 而不是 check,就是因为它只是一个类型的提示而非真正的检查。上面演示的 type hints 用法,实际上都是 ide 在帮我们完成类型检查的功能,但实际上,ide 的类型检查并不能决定代码执行期间是否报错,仅能在静态期做到语法检查提示的功能。

要想实现在代码执行阶段强制对类型进行检查,则需要我们通过自己编写代码或引入第三方库的形式(如上面介绍的 pydantic)。下面我通过一个 type_check 函数实现了运行期动态检查类型,来供你参考:

  from inspect import getfullargspec  from functools import wraps  from typing import get_type_hints      def type_check(fn):      @wraps(fn)      def wrapper(*args, **kwargs):          fn_args = getfullargspec(fn)[0]          kwargs.update(dict(zip(fn_args, args)))          hints = get_type_hints(fn)          hints.pop("return", none)          for name, type_ in hints.items():              if not isinstance(kwargs[name], type_):                  raise typeerror(f"expected {type_.__name__}, got {type(kwargs[name]).__name__} instead")          return fn(**kwargs)        return wrapper      # name: str = "world"  name: int = 2    @type_check  def greeting(name: str) -> str:      return str(name)    print(greeting(name))  # > typeerror: expected str, got int instead    

只要给 greeting 函数打上 type_check 装饰器,即可实现运行期类型检查。

附录

如果你想继续深入学习使用 python type hints,以下是一些我推荐的开源项目供你参考:

pydantic 

fastapi 

tornado 

flask 

chia-pool 

mysqlhandler 

以上就是python type hints 学习之从入门到实践的详细内容,更多关于python type hints的资料请关注<计算机技术网(www.ctvol.com)!!>其它相关文章!

需要了解更多python教程分享Python Type Hints 学习之从入门到实践,都可以关注python教程分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/pythontutorial/964876.html

(0)
上一篇 2021年12月2日
下一篇 2021年12月2日

精彩推荐