Title: Defining __init__ in enums
Type: behavior Stage: patch review
Components: Documentation, Library (Lib) Versions: Python 3.8, Python 3.7, Python 3.6
Status: open Resolution:
Dependencies: Superseder:
Assigned To: ethan.furman Nosy List: barry, eli.bendersky, ethan.furman, killerrex, miss-islington
Priority: normal Keywords: patch

Created on 2018-05-07 10:02 by killerrex, last changed 2018-09-12 17:00 by miss-islington.

File name Uploaded Description Edit
enum_allow_change_value_in_init.patch killerrex, 2018-05-07 10:02 Patch to allow changing _value_ in __init__ of an Enum
Pull Requests
URL Status Linked Edit
PR 9145 merged ethan.furman, 2018-09-10 22:52
Messages (5)
msg316256 - (view) Author: Andres Ayala (killerrex) * Date: 2018-05-07 10:02
I have to read and write many files for an old fortran program where the elements are coded as integer (so 0 is the X, 1 is the Y...) and I have some tags associated to each one.

So I tried to create an Enum with some additional fields:
class Coord(Enum):
    def __init__(self, value, label, unit):
        self._value_ = value
        self.label = label
        self.unit = unit

    PX = (0, 'P.X', 'km')
    PY = (1, 'P.Y', 'km')
    VX = (2, 'V.X', 'km/s')
    VY = (3, 'V.Y', 'km/s')

This almost work:
>>> for element in CoordOk:
...    print("{0}: {0.label}[{0.unit}] = {0.value}".format(element))
CoordOk.PX: P.X[km] = 0
CoordOk.PY: P.Y[km] = 1
CoordOk.VX: V.X[km/s] = 2
CoordOk.VY: V.Y[km/s] = 3

But fails recovering the coordinate from the value:
>>> print(Coord(0))
Traceback (most recent call last):
  File "/home/killerrex/tmp/", line 33, in <module>
  File "/usr/lib64/python3.6/", line 291, in __call__
    return cls.__new__(cls, value)
  File "/usr/lib64/python3.6/", line 533, in __new__
    return cls._missing_(value)
  File "/usr/lib64/python3.6/", line 546, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 0 is not a valid Coord

Because the internal value of the enum is (0, 'P.X', 'km') and not 0

I found that it is possible to do what I am trying to do with:
class CoordOk(Enum):
    def __new__(cls, value, label, unit):
        obj = object.__new__(cls)
        obj._value_ = value
        obj.label = label
        obj.unit = unit
        return obj

    PX = (0, 'P.X', 'km')
    PY = (1, 'P.Y', 'km')
    VX = (2, 'V.X', 'km/s')
    VY = (3, 'V.Y', 'km/s')

Following the latest doc from Enum. Although it is not so intuitive (defining __new__ is not as easy as __init__)

To make the first proposal work fine is enough with moving the line 221 of after the line 224 (see the patch)
I haven't found problems with the change but obviously my little reduced tests are not representative at all.
And even if it works there may be good reasons to not allow changing the _value_ in the init.

So mi enhancement proposal is either:
Add an example like the CoordOk to the documentation to help others to find how to change the _value_ (and an explanation on why is better not to do it in the __init__ would be perfect)


Change the line so it is possible to update the _value_ in the __init__ method and if you want use the Coord example in the docs.

msg316277 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2018-05-07 19:12
Setting _value_ needs to happen in __new__ for those cases where another data type, such as str or int, is mixed in.

I'll look at adding an example to the docs.

Thanks for the report!
msg316283 - (view) Author: Andres Ayala (killerrex) * Date: 2018-05-08 10:24
I see, with mixed types you need to use __new__ to construct the elements (I imagine is specially important for non mutable types)

I have modified the example of the coordinates to try to use a mixed type. Is not the most useful thing, but it mix the bytes class.
Is it not obvious how to correctly use the mixin + __new__ operator so it is easy that the example is not correct or can be done better.

class Coordinate(bytes, Enum):
    Coordinate with binary codes that can be indexed by the int code.
    def __new__(cls, value, label, unit):
        obj = bytes.__new__(cls, [value])
        obj._value_ = value
        obj.label = label
        obj.unit = unit
        return obj

    PX = (0, 'P.X', 'km')
    PY = (1, 'P.Y', 'km')
    VX = (2, 'V.X', 'km/s')
    VY = (3, 'V.Y', 'km/s')

# This works as expected
for element in Coordinate:
    print("{0}: {0.label}[{0.unit}] = {0.value}".format(element))

# And this Work
print("Obtain P.Y from the name:", Coordinate['PY'])
print("Obtain V.Y from the index:", Coordinate(3))

# This shall be False
print('Coordinate.PY == 1 is:', Coordinate.PY == 1)
# But this shall be True
print("Coordinate.PY == b'\\01' is:", Coordinate.PY == b'\01')

msg316288 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2018-05-08 15:01
That new example looks great!  Note that you don't need the parenthesis, though.

FYI: The same thing using the aenum library* would look like:

    from aenum import Enum

    class Coord(bytes, Enum):
    _init_ = 'value label unit'

    PX = [0], 'P.X', 'km'
    PY = [1], 'P.Y', 'km'
    VX = [2], 'V.X', 'km/s'
    VY = [3], 'V.Y', 'km/s'

* aenum is the Advanced Enum library I wrote that has a few extra abilities.
msg325146 - (view) Author: miss-islington (miss-islington) Date: 2018-09-12 17:00
New changeset f52237400b9960d434c5d0676a3479b8c1e8c869 by Miss Islington (bot) (Ethan Furman) in branch 'master':
bpo-33437: add __new__ vs __init__ example (GH-9145)
Date User Action Args
2018-09-12 17:00:42miss-islingtonsetnosy: + miss-islington
messages: + msg325146
2018-09-10 22:52:39ethan.furmansetstage: patch review
pull_requests: + pull_request8593
2018-05-08 15:01:04ethan.furmansetmessages: + msg316288
2018-05-08 10:24:07killerrexsetmessages: + msg316283
2018-05-07 19:12:28ethan.furmansetassignee: ethan.furman
type: enhancement -> behavior
components: + Documentation
versions: + Python 3.7, Python 3.8
nosy: + barry, eli.bendersky, ethan.furman

messages: + msg316277
2018-05-07 10:02:37killerrexcreate