惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
罗磊的独立博客
F
Fortinet All Blogs
人人都是产品经理
人人都是产品经理
量子位
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
M
MIT News - Artificial intelligence
B
Blog RSS Feed
腾讯CDC
博客园_首页
aimingoo的专栏
aimingoo的专栏
博客园 - 三生石上(FineUI控件)
博客园 - Franky
S
SegmentFault 最新的问题
N
Netflix TechBlog - Medium
小众软件
小众软件
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LINUX DO - 热门话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Martin Fowler
Martin Fowler
D
Docker
P
Privacy & Cybersecurity Law Blog
S
Securelist
V
V2EX
Jina AI
Jina AI
阮一峰的网络日志
阮一峰的网络日志
T
Tor Project blog
The Hacker News
The Hacker News
Microsoft Azure Blog
Microsoft Azure Blog
AWS News Blog
AWS News Blog
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
Help Net Security
Help Net Security
酷 壳 – CoolShell
酷 壳 – CoolShell
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 叶小钗
Recent Announcements
Recent Announcements
Cloudbric
Cloudbric
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Latest news
Latest news
MongoDB | Blog
MongoDB | Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recorded Future
Recorded Future
V2EX - 技术
V2EX - 技术

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例) 读《为什么学生不喜欢上学》 OpenAI Prompt Engineering 摘录和总结 读《打造真正的新产品》 VueJS 总结 Linux 自动挂载 alist 提供的webdav FreeBSD 使用 vm-bhyve 安装Debian虚拟机 FreeBSD 和 Linux 网卡聚合实现提速 GPT 帮我搞定了时区转换问题 长任务系统如何处理? macOS/Linux 编译 InputLeap 使用开源软KVM - synergy-core 解决 macOS 终端hostname一直变化问题 KVM 共享 Intel 集成显卡 PromQL 备忘 读《格鲁夫给经理人的第一课》 读《打开心智》 为什么要把复杂的联表操作拆成多个单表查询? 红包系统的设计 MySQL Index Condition Pushdown Optimization Go mod 简明教程 OpenWRT 使用 Android/iOS USB 网络 搭建旁路由 Golang gRPC 错误处理 编写可维护的单元测试代码 OAuth 2 详解(六):Authorization Code Flow with PKCE OAuth 2 详解(五):Device Authorization Flow OAuth 2 详解(三):Resource Owner Password Credentials Grant OAuth 2 详解(四):Client Credentials Flow OAuth 2 详解(二):Implict Grant Flow OAuth 2 详解(一):简介及 Authorization Code 模式 ElasticSearch 学习笔记 三种git流程以及发版模型 错误处理实践 权限模型(RBAC/ABAC) OIDC(OpenID Connect) 简介 任务队列简介 PostgreSQL 操作笔记 使用Drone CI构建CI/CD系统 Golang migrate 做数据库变更管理 使用PostgreSQL做搜索引擎 Nginx 源码阅读(三): 连接池、内存池 Nginx 源码阅读(二): 请求处理 Nginx 源码阅读(一): 启动流程 Go 泛型简明教程 KVM 显卡穿透给 Windows 使用 HTTP Router 处理 Telegram Bot 按钮回调 使用反射(reflect)对结构体赋值 GIN 是如何绑定参数的 你好 2022(2021 年终总结) 用Go导入大型CSV到PostgreSQL 使用 OpenWRT 搭建软路由 使用软KVM切换器 barrier 共享键鼠 SQL 防注入及原理 使用 gomock 测试 Go 代码 gevent不是黑魔法(二): gevent 实现 gevent不是黑魔法(一): greenlet 实现 用 entgo 替代 gorm 应用内使用crontab不是那么方便 单测时要不要 mock 数据库? Sentry 自建指南 用selenium完成自动化任务 用闲置的安卓手机做垃圾电话短信过滤 推荐三个时间管理工具 一次事故反思 当JS遇到uint64:JS整数溢出问题 SQLite3 存储以及ACID原理 Redis源码阅读:pub/sub实现 Redis源码阅读:zset实现 Redis源码阅读:bitmap 位图的运算 Redis源码阅读:set是怎么做交并集运算的?
functools 源码阅读与分析
2017-01-08 · via Jiajun的技术笔记

functools主要包括这几个东西: wraps, partial, lru_cache, 还有一些内置 帮助函数例如 c3_mro。我们主要看上面三个:

wraps

wraps实现很简单,就是把a函数的某些属性拷贝到b函数。

partial

partial的实现,看下面代码就可以了:

class Partial:
    def __new__(*args, **kwargs):
        cls, func, *args = args

        self = super(Partial, cls).__new__(cls)
        self.func = func
        self.args = args
        self.kwargs = kwargs

        return self

    def __call__(*args, **kwargs):
        self, *new_args = args
        new_kwargs = self.kwargs.copy()
        new_kwargs.update(kwargs)
        return self.func(*self.args, *new_args, **new_kwargs)


mypartial = Partial  # noqa


if __name__ == "__main__":
    def foo(first, second, hello="world"):
        print("first, second, hello = %s, %s, %s" % (first, second, hello))

    bar = mypartial(foo, second=2, hello="hello")
    bar(1)

主要原理就是先用一个类来保存原函数的一些状态,然后重写 __call__ 方法,把 对应的已经partial的参数一起塞进去。

lru_cache(Least-recently-used cache)

这个比较有意思,def lru_cache(maxsize=128, typed=False):,如果maxsize为0, 那就直接返回函数结果,如果为None,那就直接用一个字典存储,如果为具体数值, 那么还会有一个环状双向链表来保存顺序。

lru_cache 的实现主要包括三个部分:

- `class _HashedSeq(list)`
- `def _make_key(...省略一把参数...)`
- `def lru_cache(maxsize=128, typed=False)`

其中第一个类用来保存hash值,第二个用来根据函数的参数生成key,第三个基于前两个 实现了lru_cache

下面是我的一个实现:

class Link:
    __slots__ = 'prev', 'next', 'key', 'value'


def _make_key(args, kwargs, kwargs_mark=(object(), )):
    key = args
    if kwargs:
        sorted_kwargs = sorted(kwargs.items())
        key += kwargs_mark
        for kwarg in sorted_kwargs:
            key += kwarg
    return hash(key)


def lru_cache(maxsize=128):
    def decorator(user_func):
        return _lru_cache_wrapper(user_func, maxsize)
    return decorator


def _lru_cache_wrapper(user_func, maxsize):
    cache = {}
    root = Link()
    root.prev, root.next, root.key, root.value = root, root, None, None

    def decorator(*args, **kwargs):
        nonlocal cache, root
        key = _make_key(args, kwargs)
        if key in cache:
            value = cache[key]
        else:
            value = user_func(*args, **kwargs)

        # 更新环状双向链表
        last = root.prev
        link = Link()
        link.prev = last
        link.next = root
        link.key, link.value = key, value
        root.prev = last.next = link

        if key not in cache:
            # 更新缓存信息和环状双向链表,因为缓存有大小限制
            cache[key] = value

            last = root.prev
            root = root.next
            root.prev = last
            last.next = root

        return value
    return decorator


if __name__ == "__main__":
    import time

    # 普通递归版fib函数
    start = time.time()

    def fib(x):
        if x == 0 or x == 1:
            return x
        else:
            return fib(x - 1) + fib(x - 2)

    result = fib(35)
    end = time.time()
    print("result: %s, use time: %.6f" % (result, end - start))

    # 为了方便看,还是不用函数形式的decorator,而是直接把fib函数抄一遍
    start = time.time()

    @lru_cache()
    def fib_cache(x):
        if x == 0 or x == 1:
            return x
        else:
            return fib_cache(x - 1) + fib_cache(x - 2)

    result = fib_cache(35)
    end = time.time()
    print("result: %s, use time: %.6f" % (result, end - start))

运行结果:

root@arch tests: python myfunctools.py
result: 9227465, use time: 4.576693
result: 9227465, use time: 0.000146