Reputation: 77
How can I explicitly define what values can given variable have? Let's say I want value of variable size to be either 'small', 'medium', or 'big' and nothing else.
EDIT: I want to avoid a situation when variable is set to something from beyond the list (for example to 'tiny' in this case). Like enum in Java. This variable would be a class field.
Upvotes: 1
Views: 8606
Reputation: 3283
You could define a Size class inside your class and then set the size attribute while checking whether the value is allowed. Below a minimal example:
from enum import Enum
class Trial:
class Size(Enum):
small = "small"
medium = "medium"
large = "large"
def __init__(self, size):
self._set_size(size)
def _set_size(self, size):
if size in set(item.value for item in self.Size):
self._size = size
else:
raise ValueError("size value not valid")
Upvotes: 3
Reputation: 1779
You are describing an enumeration
, which is supported in Python by the enum
library:
from enum import Enum
class Size(Enum):
small = 'small'
medium = 'medium'
big = 'big'
size = Size('big')
print(size)
try:
size = Size('tiny')
except ValueError as e:
print("invalid Size (", e.args[0].split()[0],
"). Size must be one of 'small', 'medium' or 'big'", sep='')
Output:
Size.big
invalid Size ('tiny'). Size must be one of 'small', 'medium' or 'big'
Upvotes: 6
Reputation: 3882
Simplest way would be to always use dedicated method which would firstly validate input and if it's correct then set variable. Below you may find some example:
class Test:
def __init__(self):
self.__variable = None
def set_variable(self, value):
if value not in ('small', 'medium', 'big'):
raise ValueError()
self.__variable = value
Upvotes: 6