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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)