Python备忘录

Python 备忘录

记录使用 Python 时的点滴。

Author: ChrisZZ imzhuo@foxmail.com
Create: 2023.05.08 12:20:00
Last Modified: 2023-05-12 13:15:05

1. Python 在 Windows 下的补全

pip install pyreadline3

2. 操作注册表: winreg 模块

包括且不限于如下作用:

  • 获取实时更新的环境变量取值
  • 获取安装了的 Visual Studio 的版本

3. 命令行调试 python 程序

使用 pdb 模块作为调试器:

python -m pdb xxx.py

注意必须提供文件名字, 这和 GDB/LLDB 不太一样。也就是说 PDB 并不是和 GDB/LLDB 兼容的, 因此在 Vim 中使用 Termdebug 时无法很好的使用 PDB 调试 Python 。

4. 列出所有模块

import sys
modules = sorted(sys.modules.keys())
for item in modules:
    print(item)

5. 类型注解(type hints)

  • 函数参数增加类型: : type
  • 函数返回值增加类型: -> type :
  • 带默认值的参数, 增加类型: : type=default_value

e.g.

def add(x, y):
    return x + y

=>

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

e.g. 2

def hello(name='Chris'):
    print("Hello, {:s}".format(name))

=>

def hello(name: str='Chris'):
    print("Hello, {:s}".format(name))

注意, type hints 并不是给到 Python 解释器做真正的类型检查, 仅仅是给人看的。也就是说你可以不按 type hints 给的类型来传入参数, 也能得到结果:

def my_add(x: int, y: int) -> int:
    return x + y

c = my_add(2.4, 5.5)
print(c) # 7.9

获取 type hint annotation

print(add.__annotations__)

e.g.

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

print(add.__annotations__) # {'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}

检查Python代码实际参数是否符合type hint annotation

使用 mypy 模块可以执行检查:

pip install mypy

e.g.

# x.py
def add(x: int, y: int) -> int:
    return x + y

c = add(2.4, 5.5)
print(c)
mypy x.py

D:\github\sledpkg>mypy x.py
x.py:4: error: Argument 1 to "add" has incompatible type "float"; expected "int" [arg-type]
x.py:4: error: Argument 2 to "add" has incompatible type "float"; expected "int" [arg-type]
Found 2 errors in 1 file (checked 1 source file)

类型别名(type aliases)

添加 type hint 时, 基础类型还算好加, 复合类型写起来显得很罗嗦。可以给已有类型起别名。

e.g.

Vector = list[float]

def scale(scalar: float, vector: Vector):
    return [scalar * num for num in vector]

new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector)
posted @ 2023-05-08 12:19  ChrisZZ  阅读(23)  评论(0编辑  收藏  举报