Steve Jorgensen wrote:
> After messing around with Enum for a while, there's one small thing that
> I'd like to see improved. It seems limiting to me that the only way to trigger
> _generate_next_value is to pass auto().
> What if, for a particular Enum, I would like to be able to use
> () as a shorthand for auto()? How about a more complex
> auto-generation that determines the final value based on both the given value 
> and the
> name/key

What's wrong with `auto()`? Why do you need a shorthand for that? Also `()` is 
an empty tuple so it's just another enum value.

> As an example of the second case, start with an Enum subclas in which each
> item, by default, has the name/key as its value and a prettified version of 
> the name as
> its label, but one can also specify the value and label using a 2-item tuple 
> for the
> value. Now, let's say we want to be able to specify a custom label and still 
> use the
> name/key as the value either as a None/label tuple or as a string starting 
> with a
> comma.

It seems that your second case can be accomplished by using a custom descriptor 
that receives the field name via `__set_name__`. For example:

    from enum import Enum


    class Value:
        def __init__(self, val):
            self.val = val
            self.name = None

        def __set_name__(self, owner, name):
            self.name = name

        def __get__(self, instance, owner=None):
            return f'{self.name} {self.val}'

        def __set__(self, instance, value):
            raise AttributeError


    class MyEnum(Enum):
        RED = Value(1)
        GREEN = Value(2)
        BLUE = Value(3)

> Using a custom test for auto, one could identify those cases, Passing the 
> assigned
> value to the _generate_next_value_ function would allow it to make use of
> that information. For backward compatibility, the signature of the
> _generate_next_value_ function can be checked to make sure it can accept the
> extra argument for that before passing that.
_______________________________________________
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/6GVFYIT6JYAWFYK6BY53AJSGQRB5L5Y6/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to