typing
typing copied to clipboard
Mark classes as not instantiable
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__asNoReturn/Never. - Set
__new__toNone(similar to how__hash__works). - A new decorator.
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.