Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
bad_coder Avatar asked Oct 26 '25 07:10

bad_coder


1 Answers

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'>]
like image 110
Ethan Furman Avatar answered Oct 28 '25 22:10

Ethan Furman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!