python / python/cpython

Add `operator.identity`, the identity function

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

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

extension-modules pending 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

Adding the identity function has come up a few times. Recently, it was noted on Discourse that the function may also be useful for deferring some runtime uses of typing imports, such as the @final and @overload decorators, where all that is needed at runtime is the identity function.

I propose to add operator.identity, a single-argument function returning the first argument. This would be implemented in both Python and C for performance, similarly to the existing _typing.idfunc, which it would replace.

Searching GitHub, this has previously been mentioned as useful for improving Python iterator performance, and comes up in discussions of API coherence for functions operating on iterators (e.g. groupby, filter, map), to avoid needing to special-case None. The topic last seems to have been substantivly discussed 17 years ago, in GH-46439 and GH-44652. There are over 300 instances of the single-argument identity function in the CPython tree, so the pattern is clearly prevalent. I would also argue that the typing use-case is both new since 2008 and compelling. Those who only use static type checkers pay a cost for the support injected by decorators such as @final or @overload which is not necessary. For such developers, a pattern such as the following would enable the benefits of static typing, whilst limiting the runtime cost as much as possible:

if TYPE_CHECKING:
    from typing import final, overload
else
    import operator
    final = overload = operator.identity

A

Linked PRs
  • gh-132342

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 bằng việc xem xét _typing.idfunc và công việc liên quan được đề xuất trong gh-132342, cùng với các cuộc thảo luận trước đây của issue về các API iterator và decorator của typing. Được coi là hoàn thành khi thêm operator.identity trong cả Python và C, bao quát hành vi với một đối số của nó và xử lý đề xuất thay thế _typing.idfunc.

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

Đánh giá

Công nghệ
c, python
Lĩnh vực
backend
Loại issue
Tính năng
Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
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.