How can I set a default value for an enum attribute of a recordclass dataobject?

Question:

recordclass dataobjects can handle enum attributes just fine, unless you need to set a default value, which results in a SyntaxError (as of version 0.17.5):


In [1]: from enum import Enum, auto

In [2]: from recordclass import dataobject

In [3]: class Color(Enum):
   ...:     RED = auto()
   ...: 

In [4]: class Point(dataobject):
   ...:     x: float
   ...:     y: float
   ...:     color: Color
   ...: 

In [5]: pt = Point(1, 2, Color.RED)

In [6]: pt
Out[6]: Point(x=1, y=2, color=<Color.RED: 1>)

In [7]: class Point(dataobject):
   ...:     x: float
   ...:     y: float
   ...:     color: Color = Color.RED
   ...: 
   ...: 
Traceback (most recent call last):
...
  File "<string>", line 2
    def __new__(_cls_, x, y, color=<Color.RED: 1>):
                                   ^
SyntaxError: invalid syntax

Is there a workaround for this issue?

Asked By: Andrew Eckart

||

Answers:

Assuming the example in the question is accurate, you’ll need to override the stardand Enum.__repr__():

class Color(Enum):
    #
    def __repr__(self):
        return f'{self.__class__.__name__}.{self._name_}'
    #
    RED = auto()
Answered By: Ethan Furman

Since 0.18 one may use default value of any type.

from recordclass import dataobject
from enum import Enum, auto

class Color(Enum):
    RED = auto()

class Point(dataobject):
    x: float
    y: float
    color: Color = Color.RED

>>> pt = Point(1,2)
>>> pt
Point(x=1, y=2, color=<Color.RED: 1>)
>>> pt.color
<Color.RED: 1>
>>> type(pt.color)
<enum 'Color'>
Answered By: intellimath
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.