pythonclassenumsconstructorpython-3.4

Is it possible to call the constructor of a class that inherits Enum without arguments?


I have multiple classes, some inherit Enum, others don't and all of them end up mixed in big arrays such as show below:

from enum import Enum

class TestEnum(Enum):
    VAL_A = 0
    VAL_B = 1

class TestNotEnum():
    def __init__(self):
        self.var = 1

As I wish to have a code as simple as possible for others to use, I would like to call the constructors of all the classes the same way to avoid as much confusion as possible.

This is how I would like to initialize them :

classes = [TestEnum(), TestNotEnum()]

The TestNotEnum class has no issues with it but the TestEnum throws the following exception : TypeError: __call__() missing 1 required positional argument: 'value'. This is due to my (bad) use of Enum.

What can I do in order to have the TestEnum class still inherit Enum and yet have a constructor that has no arguments ?

I tried the following ( and a few similar tweaks ):

class TestEnum(Enum):
    VAL_A = 0
    VAL_B = 1
    def __init__(self):
        super(TestEnum, self).__init__()

but I only end up with different errors such as TypeError: __init__() takes 1 positional argument but 2 were given


Solution

  • Thanks to @glibdud who commented my question => it is not possible as show here : all Enum classes are Singletons and therefor I cannot call the construction the way I wished to do.

    The other given solutions are interesting but did not fit my needs ( aenum adds new constraints and factory functions add a new layer of complexity for the API user )

    An other possibility would have been to make my own Enum class that fit my needs but I chose to redo my architecture instead as it was faster : instead of putting class instances this way classes = [TestEnum(), TestNotEnum()], I placed the references classes = [TestEnum, TestNotEnum] as a template array and the wished values in a second array of same size.

    Not as good as a solution I would have liked but it works and allows the API user to do minimal work as he doesn't edit the template arrays.