Search code examples
pythonpython-3.xenumsreserved-wordsreserved

Reserved word as member of enum


I wanted to make a python Enum work having a reserved word as member.

class Test(Enum):

    one = "one"
    is_ = "is"

I wanted to customize __name__ to have the usual syntax return

>>> print(Test.is_.name)
is

So how do I customize __name__, __getattribute__ or __getattr__ to accomplish this?


Solution

  • Instead of mucking about with the internals, you could use the Functional API instead:

    Test = Enum('Test', [('one', 'one'), ('is', 'is'), ('is_', 'is')])
    

    and in use:

    >>> Test.one
    <Test.one: 'one'>
    
    >>> Test.is
      File "<stdin>", line 1
        test.is
              ^
    SyntaxError: invalid syntax
    
    >>> Test.is_
    <Test.is: 'is'>
    
    >>> Test['is']
    <Test.is: 'is'>
    
    >>> Test['is_']
    <Test.is: 'is'>
    
    >>> Test('is')
    <Test.is: 'is'>
    
    >>> list(Test)
    [<Test.one: 'one'>, <Test.is: 'is'>]