[New-bugs-announce] [issue26266] add classattribute to enum to handle non-Enum attributes

Ethan Furman report at bugs.python.org
Tue Feb 2 11:27:31 EST 2016


New submission from Ethan Furman:

The rules for what objects in an Enum become members and which do not are fairly straight-forward:

__double_underscore__ do not (but is reserved for Python)
_single_underscore_ do not (but is reserved for Enum itself)
any descriptored object (such as functions) do not

Which means the proper way to add constants/attributes to an Enum is to write a descriptor, but most folks don't think about that when the Enum is not working properly they (okay, and me :/ ) just add the double-underscore.

This question has already come up a couple times on StackOverflow:
- http://stackoverflow.com/q/17911188/208880
- http://stackoverflow.com/q/34465739/208880

While this doesn't come up very often, that just means it is even more likely to have the attribute be __double_underscored__ instead of descriptored.

The solution is have a descriptor in the Enum module for this case.  While it would be possible to have several (constant-unless-mutable, constant-even-if-mutable, not-constant, possibly others) I think the not-constant would be sufficient (aka a writable property), although I am not opposed to a constant-unless mutable version as well.

The not-constant version would look like this (I'll attach patch later):

class classattribute:
    def __init__(self, value):
        self.value = value
    def __get__(self, *args):
        return self.value
    def __set__(self, value):
        self.value = value
    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self.value)

----------
assignee: ethan.furman
messages: 259399
nosy: barry, eli.bendersky, ethan.furman
priority: normal
severity: normal
status: open
title: add classattribute to enum to handle non-Enum attributes
type: behavior
versions: Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue26266>
_______________________________________


More information about the New-bugs-announce mailing list