Skip to content

'Any' with a bound? #8981

Description

@mthuurne

When mypy is run on the following code:

from typing import Any, Generic, TypeVar

T = TypeVar('T', bound=int)

class C(Generic[T]):
    x: T

c: C[Any] = C()
c.x = 123
c.x = 'abc'

It will not report any errors. However, since T has int as a bound, assigning a string to x should be considered invalid even if we don't know the exact type of x.

It seems that when Any is substituted for the type argument of C, the knowledge of the bound is lost. Perhaps AnyType could be given a bound, object by default, to restrict which types Any can represent in a particular context.

Activity

  1. Kangaroux commented on Jun 10, 2020

    @Kangaroux

    https://docs.python.org/3/library/typing.html#typing.TypeVar

    Alternatively, a type variable may specify an upper bound using bound=. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type [...]

    I think it should report an error for c: C[Any] = C() rather than c.x = 'abc', since Any is a superset of int, not a subset.

  2. mthuurne commented on Jun 10, 2020

    @mthuurne
    ContributorAuthor

    https://docs.python.org/3/library/typing.html#typing.TypeVar

    Alternatively, a type variable may specify an upper bound using bound=. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type [...]

    I think it should report an error for c: C[Any] = C() rather than c.x = 'abc', since Any is a superset of int, not a subset.

    The typing module documentation you linked describes Any as:

    Special type indicating an unconstrained type.

    • Every type is compatible with Any.
    • Any is compatible with every type.

    Since it's compatible in both directions, I think C[Any] is valid.

  3. Akuli commented on Jul 25, 2020

    @Akuli
    Contributor

    Plain C is same as C[Any]. Should that be C[bound of T] instead?

  4. erictraut commented on Aug 11, 2023

    @erictraut

    This issue appears to be based on a misunderstanding of how Any works in the Python type system. For details about how Any is meant to work and why it exists, refer to PEP 483.

    The use of Any as a type argument is especially important in cases where the type parameter is invariant, as the use of any concrete type such as object or bound of T will result in invariant type incompatibilities.

    Mypy is doing the right thing in how it's treating Any, and it would be inappropriate to emit an error in any of the above cases.

    I recommend closing this issue.

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