1

I would like to use isinstance() method to identify class variable is it belongs to the given class.

I created an own Enum() base class to list class variables of subclasses. I did't detail body of source code, not important.

class Enum(object):

    @classmethod
    def keys(cls):
        pass  # Returns all names of class varables.

    @classmethod
    def values(cls):
        pass  # Returns all values of class varables

    @classmethod
    def items(cls):
        pass # Returns all class variable and its value pairs.

class MyEnum(Enum):
    MyConstantA = 0
    MyConstantB = 1

>>>MyEnum.keys()
['MyConstantA', 'MyConstantB']

I would like to use this one:

>>>isinstance(MyEnum.MyConstantB, MyEnum)
True
HelloWorld
  • 2,392
  • 3
  • 31
  • 68

2 Answers2

0

Enum became an official data type in Python 3.4, and there is a backport here, with docs here.

isinstance() works as you would like, and to get the names of the members you would use:

myEnum.__members__.keys()

While both MyEnum['MyConstantA'] and MyEnum(0) would return the MyEnum.MyConstantA member.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
-2

It seems that an ordinary dictionary can do what you want:

>>> myEnum = {'MyConstantA': 0, 'MyConstantB': 1}

Or let enumerate do the counting:

>>> myEnum = {k: i for i, k in enumerate(['MyConstantA', 'MyConstantB'])}

Then:

>>> myEnum.keys()
['MyConstantA', 'MyConstantB']
>>> myEnum.values()
[0, 1]
>>> myEnum.items()
[('MyConstantA', 0), ('MyConstantB', 1)]
>>> 'MyConstantB' in myEnum
True

In case you really want to write your own class, use hasattr to test the existence of class variables:

>>> class Foo:
...     bar = 5
...
>>> hasattr(Foo, 'bar')
True
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    The goal is to achieve the isinstance() usage. This implementation is a part of bigger structure, that's why would be great if isinstance() can work some way. – David Lantos Sep 29 '15 at 11:38