typing icon indicating copy to clipboard operation
typing copied to clipboard

Mark classes as not instantiable

Open srittau opened this issue 5 months ago • 1 comments

From python/typeshed#14558: Some classes (like re.Pattern) are not instantiable at runtime:

>>> import re
>>> re.Pattern()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot create 're.Pattern' instances

Currently, there is no working way to mark classes as such. Ideas to mark classes:

  • Annotate the return type of __new__ as NoReturn/Never.
  • Set __new__ to None (similar to how __hash__ works).
  • A new decorator.

srittau avatar Aug 11 '25 10:08 srittau

In a project of mine, I have a Rust extension (built with pyo3) where some classes cannot be instantiated from Python. I'm currently using this approach, which seems to be working (with pyright, I have not tried mypy yet):

# mymodule.pyi
from typing import Never

class Foo:
   def __init__(self: Never, /) -> None: ...  # valid because `Never <: Foo`

x = Foo()  # error because `Foo <: Never` is false

However, I would really appreciate it if there was an official way to do this.

RBerga06 avatar Aug 11 '25 12:08 RBerga06