Python3 Typing
date
May 11, 2021
slug
python3 typing
status
Published
tags
python
summary
type
Post
python 的 typing 能帮助 IDE 更好地判断变量的类型,写代码的过程效率会高很多,重构的过程也会轻松很多。在多人协作的项目中,也能减少沟通的成本和误解。typing 的一般用法还是很好上手的,本篇 blog 主要记录几个不那么常见的问题。
定义回调函数的参数类型
传回调函数时,可以定义回调函数的传参和返回结果类型
from typing import Callable def callback(arg1: int, arg2: int) -> str: s = f"arg1: {arg1} arg2: {arg2}" return s class B: # syntax is Callable[[Arg1Type, Arg2Type], ReturnType] def foo(self, func: Callable[[int, int], str]): print(func(1, 2)) if __name__ == "__main__": b = B() b.foo(callback)
以当前文件中的类型为 typing
如果需要 typing 的类型在文件中已经定义好了,那可以直接引用
class A: pass class B: def foo(self, a: A): pass
如果
B
类先定义,则可以添加双引号来引用 A
类。class B: def foo(self, a: "A"): pass class A: pass
如果是 python 3.7+ 以上的版本,可以使用
from __future__ import annotation
,这样就不需要双引号。typing 导致的循环引用
如果
class A
和 class B
定义在两个文件中,且需要相互引用时,会出现循环引用的问题,文件结构:project_dir/ | | - a.py | - b.py
a.py
的文件内容from b import B class A: def bar(self, b: B = None): print("bar")
b.py
的文件内容from a import A class B: def foo(self, a: A = None): print("bar") if __name__ == "__main__": b = B() b.foo()
如果我们执行
b.py
,这时会报 cannot import name 'A'
的错误。对 b.py
进行如下修改就可以解决该问题,注意 A
的 typing 两边一定要加「双引号」,当然在设计上应该劲量避免出现循环引用的情况。import typing if typing.TYPE_CHECKING: from a import A class B: def foo(self, a: "A" = None): print("foo") if __name__ == "__main__": b = B() b.foo()