beesleep
beesleep

Reputation: 1362

Setting nested enum value as default parameter in class __init__

I have a nested enum which holds two possible value for a parameter of a class. I would like to give on enum as the default value for the class in the __init__

Something that would look like that:

from enum import IntEnum as IntEnum
class A:
    class AParam(IntEnum):
        TYPE_1 = 1
        TYPE_2 = 2
    def __init__(self, param=A.AParam.TYPE_1):
        self.param = param

Of course It dosen't work, I guess because the class is not fully constructed yet.

The alternative solution I'm doing right now is this:

from enum import IntEnum as IntEnum
class A:
    class AParam(IntEnum):
        TYPE_1 = 1
        TYPE_2 = 2

    def __init__(self, param=None):
        if param is None:
            param = A.AParam.TYPE_1
        self.param = param

For several reasons, I don't want to use strings instead of enums. I could use also not put the parameter in the init, and just let the class user use the member variable itself. But then the default parameter is not so explicit.

Is there another way of passing nested enum as default value for the __init__ method ? Or is that just not possible...?

Upvotes: 0

Views: 441

Answers (1)

blubberdiblub
blubberdiblub

Reputation: 4135

You can regard the inside of the class as a scope, not unlike the scope inside a function.

Therefore, you can do this:

class A:

    class AParam(IntEnum):
        TYPE_1 = 1
        TYPE_2 = 2

    def __init__(self, param=AParam.TYPE_1):
        self.param = param

Note the missing A..

This scope is active during the definition of the contents of the class.

Upvotes: 1

Related Questions