Python enum34 access by name
Asked Answered
R

1

9

I am using the Enum backport enum34 with Python 2.7.

According to the documentation it should be possible to access enum members by their name, using item access. That is, the following should work:

from enum import Enum

class Foo(Enum):
    bar = 1
    baz = 2

print(Foo['bar'])

However, when I run the code I get this error in the last line:

TypeError: 'type' object has no attribute '__getitem__'

Am I missing something here or is this functionallity just not implemented in the 2.7 backport?

Rutharuthann answered 22/9, 2015 at 14:50 Comment(4)
Works for me (both Python 2 and Python 3).Pinkham
@vaultah: I just tested it in a new, virgin virtualenv where I only installed enum34 and there it worked. So maybe there is a conflict with some other package? Any idea how I can trace this?Rutharuthann
What does import enum; print(enum.__file__) tell you is imported? You perhaps have a different module installed elsewhere. Then compare that file with the new virtualenv lib/python2.7/site-packages/enum/ package contents to see if you have an old version.Rivers
@MartijnPieters Yepp, it was indeed using a different module. Thanks for your help.Rutharuthann
C
8

You might be getting a conflict with the Enum module. Try this:

pip uninstall Enum

With both Enum and Enum34 installed, this did not work. After uninstalling Enum, it worked like a charm.

Chapland answered 22/9, 2015 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.