Type-hint a custom class enum

Question:

I have a enum class, which is class variable inside person class. I am getting typehint error for types class variable.

I tried as below to typehint types class variable.

  • XyzTypes
  • "XyzTypes"
  • Type[XyzTypes]
  • TypeVar["T"]

None of them work. Getting error as error: Incompatible types in assignment...

class XyzTypes(StrEnum):

    MNO: str = "mno"
    PQR: str = "pqr"
    
    @classmethod
    def get_default(cls) -> str:
        return cls.MNO
class Person:

    types: XyzTypes = XyzTypes
    

Accessing as Person.types.get_default()

Please help.

Edit: 1
I am using python 3.11

Edit: 2

Further I modified the code and made that variable private as below

class Person:

    _types: type[XyzTypes] = XyzTypes  # Working now

    @classmethod
    def get_type_enum(cls) -> ???:
        return cls._types
    

I tried below

  • type[XyzTypes]
  • "XyzTypes"

Getting error as error: Incompatible return value type

Asked By: winter

||

Answers:

If you want Person.types to refer to the class XyzTypes (or a subclass thereof), the correct type hint is

class Person:
    types: type[XyzTypes] = XyzTypes

More generally, if Person.types just needs to be an enumerated type, use

from enum import EnumType


class Person:
    types: EnumType = XyzTypes

where all enumerated types are instances of the (meta)class EnumType.

Answered By: chepner
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.