Stephane Bersier
Stephane Bersier

Reputation: 769

Type annotation for specific Enum value

Is there a way in Python to get a type annotation for a specific enum value (rather than the whole enum)? For example, the following code tries to use a type annotation for Binary.One, which would be a subtype of Binary:

from enum import Enum, auto
from typing import TypeVar, Generic

class Binary(Enum):
    One = auto()
    Two = auto()

B = TypeVar('B', bound=Binary)

class Foo(Generic[B]):
    pass

F = TypeVar('F', bound=Foo[Binary.One])

However, it raises the following warning:

Expected type 'Optional[type]', got 'Binary' instead

Upvotes: 2

Views: 1234

Answers (1)

user2357112
user2357112

Reputation: 280648

You're using type variables wrong.

B = TypeVar('B', bound=Binary) is a type variable restricted to Binary and its subtypes, not to instances of Binary. (It's a type variable, after all, and Binary.One isn't a type.) You can't create subclasses of Binary, so there aren't a lot of things B can be. It's basically restricted to Binary and to static type stuff that isn't a "real" type at runtime, like Any or literal types.

typing does not currently provide a way to create generic classes with enum values as parameters. It is possible to use a type typing.Literal[Binary.One], which is a type whose sole instance is Binary.One, and then use that as a type parameter:

Foo[Literal[Binary.One]]

Upvotes: 4

Related Questions