Home > Software engineering >  Way to simplify enum?
Way to simplify enum?

Time:10-29

Is there a better way to initialize all this boilerplate?

class Type(Enum):
    Null=auto()
    Bool=auto()
    Int=auto()
    Float=auto()
    Decimal=auto()
    String=auto()
    Bytes=auto()
    Date=auto()
    Time=auto()
    Datetime=auto()
    Timestamp=auto()
    Interval=auto()
    Struct=auto()
    Array=auto()
    Json=auto()

I wanted to do something like the following but unfortunately it kind of screws up how Pylance works (everything shows up as an error referencing related types):

_Types = ['Null','Bool','Int','Float','Decimal','String','Bytes','Date','Time','Datetime','Timestamp','Interval','Struct','Array','Json']
Type = Enum('Type', {v:i for i,v in enumerate(_Types)})

CodePudding user response:

I can't speak for Pylance, but if you want auto implementations, you can just pass your list of types directly to the Enum function.

Type = Enum('Type', ['Null','Bool','Int','Float','Decimal','String','Bytes',
                     'Date','Time','Datetime','Timestamp','Interval','Struct',
                     'Array','Json'])
  • Related