简体   繁体   中英

How to type hint that a variable should be a variable from another class?

I have the following code and the Book class has a type variable. I've added str as the type hint but the type should be either TYPE_ONE , TYPE_TWO or TYPE_THREE from the Type class.

How can I do this?

class Type:
    TYPE_ONE = 'one'
    TYPE_TWO = 'two'
    TYPE_THREE = 'three'


@dataclass(frozen=True)
class Book:
    title: str
    description: str
    type: str  # type should be one attribute of the `Type` class

You should use an enum instead:

from enum import Enum

class Type(Enum):
    TYPE_ONE = 'one'
    TYPE_TWO = 'two'
    TYPE_THREE = 'three'


@dataclass(frozen=True)
class Book:
    title: str
    description: str
    type: Type

Reference: https://docs.python.org/3/library/enum.html

Edit:

Another solution I can think of without using enums is to use NewType :

from typing import NewType

TypeAttr = NewType("TypeAttr", str)


class Type:
    TYPE_ONE: TypeAttr = TypeAttr('one')
    TYPE_TWO: TypeAttr = TypeAttr('two')
    TYPE_THREE: TypeAttr = TypeAttr('three')


@dataclass(frozen=True)
class Book:
    title: str
    description: str
    type: TypeAttr

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

Unfortunately, it can easily be broken by doing:

b = Book("title", "description", TypeAttr("not Type attribute"))

but I can't think on another solution right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM