Skip to content

Context surprise: Value of type variable "AnyStr" of "f" cannot be "object" #3876

Closed
@gvanrossum

Description

@gvanrossum

In this example, good() and bad() are equivalent, yet only bad() produces an error:

from typing import AnyStr, Iterable, List, Set, Text
def f(a: Iterable[AnyStr]) -> List[AnyStr]: ...
def good(a: List[Text]) -> Set[Text]:
    fa = f(a)
    return set(a) - set(fa)
def bad(a: List[Text]) -> Set[Text]:
    return set(a) - set(f(a))  # E: Value of type variable "AnyStr" of "f" cannot be "object"

It seems the set subtraction operator passes along some context and this gets misinterpreted. Note that because of the declared type of a, the generic calls to f(a) should always substitute Text for AnyStr, but somehow (maybe in the solver) object gets tried and fails.

A simpler version shows this perhaps better:

from typing import AnyStr, Iterable, List, Set
def f(a: Set[AnyStr]) -> Set[AnyStr]: ...
def good(a: Set[str]) -> Set[str]:
    fa = f(a)
    return set(a) - set(fa)
def bad(a: Set[str]) -> Set[str]:
    return a - f(a)  # TWO errors here

This gives two errors:

__tmp__.py:10: error: Value of type variable "AnyStr" of "f" cannot be "object"
__tmp__.py:10: error: Argument 1 to "f" has incompatible type Set[str]; expected Set[object]

How exactly it could end up trying Set[object] is a mystery to me (but then, I didn't look at the source yet).

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions