Skip to content

no error when using covariant or contravariant TypeVar on class with writable attribute #14588

Closed as not planned

Description

@DetachHead
from typing import Generic, TypeVar

T = TypeVar("T", covariant=True)


class Foo(Generic[T]):
    def __init__(self, value: T) -> None:
        self.foo = value

here, T is used in both an in and out position as the value can be modified as well.

jailbreak:

objects = Foo[object](None)

ints = Foo[int](1)


def do_thing(value: Foo[object]) -> None:
    value.foo = "asdf"


do_thing(ints)

if TYPE_CHECKING:
    reveal_type(ints.foo) # int
print(ints.foo) # "asdf" (hacked!!!!!!)

playground

Activity

  1. changed the title [-]no error when using `covariant` or `contravariant` `TypeVar` on class with readable & writable attribute[/-] [+]no error when using `covariant` or `contravariant` `TypeVar` on class with writable attribute[/+] on Feb 2, 2023
  2. hauntsaninja commented on Feb 2, 2023

    @hauntsaninja
    Collaborator

    Thanks, I think this is basically just a special case of #3208

  3. hauntsaninja commented on Feb 2, 2023

    @hauntsaninja
    Collaborator

    Posted a comment in that issue, so if we ever do something about that we will also do something about 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

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions