Skip to content

Type check signature of __new__ #1019

Open

Description

@JukkaL

We should verify that the signature of __new__ is compatible with the signature of __init__, and that the return type is not arbitrary.

Activity

  1. JukkaL commented on Nov 29, 2015

    @JukkaL
    CollaboratorAuthor

    This is follow-up to #982.

  2. gvanrossum commented on Nov 29, 2015

    @gvanrossum
    Member

    Except for the special case where the implementation for one or the other is inherited from object. In that case the signature of the one that's overridden prevails.

  3. msullivan commented on Sep 19, 2018

    @msullivan
    Collaborator

    A test case

    class A:
        def __init__(self, x: int) -> None:
            pass
    
    class B(A):
        def __new__(cls) -> 'B':
            return object.__new__(cls)
    
    B()
    

    even though it crashes at runtime.

    Per #5642 (review):
    The rule CPython uses is this (for a class C with superclass B, where B is not object):

    • If both C.__new__ and C.__init__ refer to their versions in object, the signature is def () -> C.
    • If exactly one of C.__new__ and C.__object__ refers to its object version, the other determines the signature.
    • If both override their corresponding object versions, they must match -- even if they don't come from the same class (say, if one comes from C and the other from B).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions