Skip to content

Mark classes as not instantiable #2066

Open

Description

@srittau

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.

Activity

  1. added
    topic: featureDiscussions about new features for Python's type annotations
    on Aug 11, 2025
  2. RBerga06 commented on Aug 11, 2025

    @RBerga06

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions