Peeking at the source for Enum, the __new__ method is explicitly called,
thereby deferring the call to __init__ until it, too, is explicitly
called, but only after member's _name_ attribute has been assigned. So,
adapting your example:


class ChoiceEnum(Enum):
    def __init__(self, value):
        self.label = self.name.capitalize()

class Color(ChoiceEnum):
    SMALL = 'S'
    MEDIUM = 'M'
    LARGE = 'L'

print(Color.SMALL.label)  # Prints 'Small'


Side note:
I was surprised to find the docs lacking a clear example to explain this
behaviour, the DuplicateFreeEnum recipe does show that members'
name/_name_ attributes can be accessed, via the __init__, but that info
could have more attention drawn to it rather than being somewhat buried
in an example where it isn't necessarily immediately obvious.

This is especially true considering the specific "When to use __new__()
vs. __init__()" section, which reads:

> __new__() must be used whenever you want to customize the actual value
> of the Enum member. Any other modifications may go in either __new__()
> or __init__(), with __init__() being preferred.

The second sentence, as per this thread, is demonstrably untrue.
Modifications that are reliant upon the name of the member *must* go in
__init__ (in cases where _generate_next_value_ & auto() are
inappropriate).
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/AEEXXQGEMBX2BQWXWO5TZEAYJBPYXJAZ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to