Page 1 of 1

Enums use

Posted: Mon Jun 12, 2017 5:40 pm
by decompile
Hey Guys,

Im thinking about store options in Enum Classes, like sizes to use or other stuff.

Is there a way to get more behind the value as a return?

Im right now using another function to get its values by hardcoding the values, like:

Syntax: Select all

def get_info(ColorSize):
if ColorSize == ColorSizes.SMALL:
name = 'Small'
prefix = '_small'
...


Is there a better way to do this, maybe directly in the same class?

Re: Enums use

Posted: Mon Jun 12, 2017 6:32 pm
by Ayuto
You could use something like this:

Syntax: Select all

from enum import Enum

class ColorSizes(tuple, Enum):
SMALL = ('Small', '_small')
BIG = ('Big', '_big')

print(ColorSizes.SMALL)
print(ColorSizes.SMALL.value)
Output:

Code: Select all

ColorSizes.SMALL
('Small', '_small')


Off-topic:
It's very untypical to use CamelCase for variable names. Better use color_size.


Edit:
This one is a little bit prettier.

Syntax: Select all

from enum import Enum
from collections import namedtuple

ColorSize = namedtuple('ColorSize', ['name', 'prefix'])

class ColorSizes(ColorSize, Enum):
SMALL = ('Small', '_small')
BIG = ('Big', '_big')

print(ColorSizes.SMALL)
print(ColorSizes.SMALL.value)
print(ColorSizes.SMALL.value.name)
print(ColorSizes.SMALL.value.prefix)
Output:

Code: Select all

ColorSizes.SMALL
ColorSize(name='Small', prefix='_small')
Small
_small