Skip to content

Allowing typing.NoReturn as a return hint for __init__ methods #10342

Closed

Description

@bzoracler

Feature

Allow typing.NoReturn as a return hint for __init__ methods, instead of constraining it to just None.

Pitch

The following is valid Python code:

class A:
    def __init__(self):
        raise RuntimeError
>>> A()
Traceback (most recent call last):
    ...
RuntimeError

Many projects using Boost.Python will employ its option to define classes exported to Python which aren't meant to be instantiated directly in Python, but rather via helper functions/methods, and attempts to instantiate these classes directly in Python will look like the above. These are created by defining a boost::python::class with boost::python::no_init, and interfacing with the Python API typically looks like the following:

>>> import MyBoostPythonModule  # A binary library
>>>
>>> # The final ancestor is `builtins.object`, just like standard Python classes.
>>> # Verify that this is `True`
>>> MyBoostPythonModule.MyNoInitClass.__mro__
(MyBoostPythonModule.MyNoInitClass, Boost.Python.instance, object)
>>> MyBoostPythonModule.MyNoInitClass.__mro__[-1] is object
True
>>>
>>> # Bad attempt at instantiation
>>> # See https://github.com/boostorg/python/blob/f5d14ef15e98838b3cf18692d46c481287ed50d0/src/object/class.cpp#L656-L674
>>> MyBoostPythonModule.MyNoInitClass()
Traceback (most recent call last):
    ...
RuntimeError: This class cannot be instantiated from Python
>>>
>>> # Example instance-getting function
>>> type(MyBoostPythonModule.GetMyNoInitClass).__mro__
(Boost.Python.function, object)
>>> MyBoostPythonModule.GetMyNoInitClass()  # OK
<MyBoostPythonModule.MyNoInitClass at 0x7fc56b2f25d0>

Having the ability to define stub classes which look like

from typing import NoReturn

class A:
    def __init__(self) -> NoReturn: ...

and to be able to use mypy to detect bad attempts at creating objects would greatly aid bug detection.

Activity

  1. changed the title [-]Allowing `typing.NoReturn` as the return hint for `__init__` methods[/-] [+]Allowing `typing.NoReturn` as a return hint for `__init__` methods[/+] on Apr 20, 2021
  2. JelleZijlstra commented on Apr 20, 2021

    @JelleZijlstra
    Member

    This also recently came up in python/typeshed#5137 (comment). Annotating __init__ as NoReturn seems like a reasonable way to indicate that a class cannot be instantiated.

  3. AlexWaygood commented on Aug 25, 2022

    @AlexWaygood
    Member

    Implemented in #13480 🎉

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions