Skip to content

Type annotation on self is not enforced correctly for generic classes #5305

Closed
@pnachum

Description

@pnachum

This code doesn't produce any type errors, but will crash at runtime when calling len with an int.

T = TypeVar('T')

class Box(Generic[T]):
    
    def __init__(self, val: T) -> None:
        self.val = val
		
    def foo(self: 'Box[str]') -> 'int':
        return len(self.val)

Box(1).foo()

Calling the foo method like this does result in a type error

Box.foo(Box(1))

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions