python / python/cpython

Adding Context Manger to threading.Timer

Đang mở
#125,500 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

stdlib type-feature
Ngôn ngữ chính
Python
Star
77.2k
Fork
35.9k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu với điểm vào threading.Timer và xem lại cuộc thảo luận được liên kết trên Discourse cùng PR gh-125501. Công việc được xem là hoàn thành khi Timer hỗ trợ cách sử dụng quản lý ngữ cảnh được đề xuất, khởi động khi vào và bị hủy khi thoát, với hành vi được kiểm thử phù hợp bởi các kiểm thử threading hiện có.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
operating-systems
Loại issue
Tính năng
Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
25/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.