On Mon, Jun 10, 2019 at 6:44 PM Steve Dower <steve.do...@python.org> wrote:
>
> I'd expect people coming from other languages to get it wrong this way too:
>
> class Status(Enum):
>      on
>      off
>
> Which will of course raise NameError and be just as opaque to the naive
> user as the AttributeError later on. I'm not sure we can do as much to
> help this case, but perhaps we can update __getattr__ to check
> __annotations__ on the class before failing and provide a clearer
> message? e.g. "AttributeError: 'on' was specified without assigning a
> value, did you use ':' instead of '='?" Or we could do this on
> construction, but that may rule out some interesting uses in the future
> if you have a need to delay specifying enum values.

As a side note, the aenum package on PyPI [1] supports this bare-name
notation with its AutoNumberEnum class, which uses some metaclass
magic to do it. aenum's code is complex, but an extremely bare-bones
version can be written in about 15 lines of code:

```
class AutoNumberDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.count = 0

    def __missing__(self, key):
        if isinstance(key, str) and key.startswith('__') and key.endswith('__'):
            raise KeyError(key)
        self[key] = self.count
        self.count += 1

class EnumType(type):
    def __prepare__(name, bases):
        return AutoNumberDict()

class Enum(metaclass=EnumType):
    pass
```

Of course, there are some cases that this doesn't handle (such as
duplicate names or bit flags), but for a one-off script or a personal
project, it could be enough.

[1] https://pypi.org/project/aenum/
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/CJIWLLZ2JEN2TH4B33PNWXFBN4OAOSSD/

Reply via email to