Skip to content

Mapping[K, V] should be key-contravariant #550

Closed

Description

@elazarg

Since the key is read only, it is exactly like any other function K->V. Is there any technical problem preventing this?

Activity

  1. gvanrossum commented on Sep 14, 2016

    @gvanrossum
    Member

    Have you tried it? (Not a rhetorical question.)

    The problem IIRC is that users expect Mapping to be covariant in the key,
    e.g. they have an object of type Mapping[str, int] and they want to be able
    to pass that off to a function that expects a Mapping[object, int].

  2. elazarg commented on Sep 14, 2016

    @elazarg
    ContributorAuthor

    But that's not type-safe, so warning about it at least makes sense - it can catch errors, whereas the other way around does not.

    I needed it (for the Expression/Node story) and it worked only after changing it to be contravariant.

  3. gvanrossum commented on Sep 14, 2016

    @gvanrossum
    Member
  4. elazarg commented on Sep 14, 2016

    @elazarg
    ContributorAuthor

    Oh, there's a gotcha - when extracting keys from it, they can be almost anything. So it should be type checked.

    So either there should be Mapping type without keys() and items(), or people will need to ask for Callable[[K], V] everywhere (which mixing with .get() means Callable[[K], Optional[V]] too). :\

  5. gvanrossum commented on Sep 14, 2016

    @gvanrossum
    Member
  6. elazarg commented on Sep 14, 2016

    @elazarg
    ContributorAuthor

    Confusing names....

  7. elazarg commented on Sep 15, 2016

    @elazarg
    ContributorAuthor

    Still, I want to note that the only cost of making K contravariant is making keys() return AbstractSet[object] instead of AbstractSet[K] (or perhaps AbstractSet[K_contra] has the same effective meaning?). I think it might be worth it since keys() is not the main use of Mapping.

    The best of both worlds is to let the user choose, like -K in scala, in the user side.

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions