Skip to content

Add __class_getitem__ to map builtin, PEP 585  #108761

Open
@sobolevn

Description

@sobolevn

Feature or enhancement

Right now it is impossible to subscribe map:

» ./python.exe
Python 3.13.0a0 (heads/main-dirty:79823c103b6, Aug 31 2023, 15:46:08) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> map[str]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'map' is not subscriptable
>>> 

I propose adding __class_getitem__ support to map, because it makes sense in some cases.
However, https://peps.python.org/pep-0585/ does not say anything about map.

First of all, map is defined as Generic in typeshed:

class map(Iterator[_S], Generic[_S]):
    def __next__(self) -> _S: ...

Full def: https://github.com/python/typeshed/blob/9552ec7f72f3190eb529aec096783c624b43bd29/stdlib/builtins.pyi#L1473-L1514

So, any person that wants to, say, return map[str] right now has to use 'map[str]' (via '' or via from __future__ import annotations).

Second, while we can treat map[T] as just Iterator[T] in parameter types, we always want to as specific as possible in return types.

Third, it is a builtin, so we assume that it is widely used. And it actually is, even in CPython's source itself we can find usages that can be annotated as map[whatever]:

Lastly, it is a one-line change (+ tests) and many other builtins and stdlib objects support that already.

I cannot really think of any major cons.

Linked PRs

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions