字典
key不存在,报错场景
dic={} dic['a'] # 报错 dic.get('a') # 不报错 返回None dic['a']=1 # 不报错,直接创建a=1的键值对 print(dic)
查看源码
cmd+click,蓝色面板里面显示了python内置是怎么实现字典的get,但是没有底层源码

方法入参
- _KT,_VT, TypeVar
TypeVar来自typing.TypeVar,用于泛型占位。
KT = TypeVar("KT") # 入参是name VT = TypeVar("VT")
用法举例
from typing import TypeVar T = TypeVar('T') def demo(x: T) -> T: return x
-
"/"
入参按照顺序传入get(k1) ✅,不允许写成k1=v1传入 get(k1=v1)❌
python的内置函数源码注册在CPython中
CPython源码:https://github.com/python/cpython/blob/main/Objects/dictobject.c#L3703
CPython是Python的解释器,由C语言实现。Python内置的函数,例如dict.get(k)的源码注册在CPython中,所以总说Python的底层是C语言。
调用顺序
.py - CPython 编译成中间码 - CPython 解释器 执行+调用c层函数
类比java : .java - jvm编译成.class中间码 - jvm解释器执行
_PyDict_Subscript(PyObject *self, PyObject *key) { Py_hash_t hash = _PyObject_HashFast(key); if (hash == -1) { dict_unhashable_type(self, key); return NULL; } return _PyDict_SubscriptKnownHash(self, key, hash); }
Argument clinic机制
c层开发者利用Argument clinic工具,实现简单声明-> 代码生成。
/*[clinic input] demo.add x: int y: int = 1 / Return x + y. [clinic start generated code]*/
Hashable
字典的key必须是hashable的。作为key的变量,在其生命周期,不会变。比如str,int等,但是数组[1,2]不行,作为key的话,内容发生变化,hash会发生变化,导致无法快速查找,视为unhashable。