Skip to content

Typing: improve error messages for invalid ParamSpec substitutions #102725

Closed as not planned
@AlexWaygood

Description

@AlexWaygood

Feature or enhancement

PEP-612 is a complex typing PEP that introduced some complex rules, both for static type checkers and for CPython at runtime. It can be hard to remember the intricacies of all these rules -- both for users and for typing maintainers.

One thing that might help here is if we had better error messages in situations where the runtime raises exceptions. For example, in the following snippet, the runtime is arguably correct in raising TypeErrors -- by the rules laid out in PEP-612, both of these are invalid substitutions for two reasons:

  1. Parameters can only be prepended to a ParamSpec in a parameters list using typing(_extensions).Concatenate.
  2. Appending parameters to a ParamSpec in a parameters list is disallowed.

However, the error messages don't mention either of these things, and are in fact pretty baffling:

Running PGUpdate|x64 interpreter...
Python 3.12.0a6+ (heads/main:12226bec25, Mar 10 2023, 17:32:23) [MSC v.1932 64 bit (AMD64)] on win32
>>> import typing as t, collections.abc as c
>>> P, T = t.ParamSpec("P"), t.TypeVar("T")
>>> c.Callable[P, T][[P, str], bool][int]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen _collections_abc>", line 501, in __getitem__
  File "<frozen _collections_abc>", line 456, in __new__
TypeError: Callable must be used as Callable[[arg, ...], result].
>>> class MyCallable(t.Generic[P, T]): ...
...
>>> MyCallable[P, T][[P, str], bool][int]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\alexw\coding\cpython\Lib\typing.py", line 354, in inner
    return func(*args, **kwds)
           ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\alexw\coding\cpython\Lib\typing.py", line 1403, in __getitem__
    raise TypeError(f"{self} is not a generic class")
TypeError: __main__.MyCallable[[~P, str], bool] is not a generic class

Previous discussion

This issue is a followup to some points raised in:

Cc. @sobolevn

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.12only security fixesstdlibPython modules in the Lib dirtopic-typingtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions