Jakebut Jakebut - 10 months ago 54
Python Question

Python - allowed values of a variable

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.

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.


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