Python - allowed values of a variable
<p>How can I explicitly define what values can given variable have? Let's say I want value of variable <strong>size</strong> to be either <strong>'small'</strong>, <strong>'medium'</strong>, or <strong>'big'</strong> and nothing else.</p>

<p>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.</p>

<p>You are describing an <code>enumeration</code>, which is supported in Python by the <code>enum</code> library:</p>

<pre><code>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='')
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>Size.big
invalid Size ('tiny'). Size must be one of 'small', 'medium' or 'big'
</code></pre>

python enums