python / python/cpython

Adding Context Manger to threading.Timer

未关闭
#125,500 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Feature or enhancement

Proposal:

Proposing to add context management to threading.Timer.

I had an issue where I didn’t want to ask the user to be patient unless they had already been waiting a while. Timer works nicely for this:

t = Timer(1, print, ("Trust me, I'm on it...",))
t.start()
time.sleep(2)
t.cancel()

Enclosing calls of start and cancel call out for context management for the obvious reasons. Sub-classing and adding it was trivial:

class Timer(Timer):
    def __enter__(self):
        self.start()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cancel()

The first example now looks like this:

with Timer(1, print, ("Trust me, I'm on it...",)):
    time.sleep(2)

Users of the threading module will probably already be familiar with the context management features of a lock. Chaining the two together is a great way to provide feedback IF it’s needed, gotta reduce that alarm fatigue!

hold_message = Timer(10, print, ("Please hold, your call is important to us...",))

with some_lock, hold_message:
    ...

Looking to exact those changes on the core library

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/adding-context-manger-to-threading-timer/64083

Linked PRs
  • gh-125501

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 threading.Timer 入口点开始,查看链接的 Discourse 讨论和 PR gh-125501。当 Timer 支持所提议的上下文管理用法,在进入时启动并在退出时取消,且该行为由现有的 threading 测试酌情覆盖时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
operating-systems
Issue 类型
功能
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。