2

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.

5
  • Define for what, or whom? Docstrings, enumerators, constants, assertions, validations or any combination could be useful. What have you got now, and what precisely is the problem with it? Commented Aug 29, 2016 at 22:18
  • Each variable already has a specific type. You size variable would be type string, unless small, medium, and large are variables that are assigned to integers. Please clarify your question though, because as of now, it is very ambiguous . Commented Aug 29, 2016 at 22:21
  • ve @JakeBut: Please give some example on what you are trying to achieve. Your requirement is not clear Commented Aug 29, 2016 at 22:32
  • 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. Commented Aug 29, 2016 at 22:43
  • 1
    You could try finding a programming language where this is possible. Commented Aug 29, 2016 at 22:44

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

11 Comments

He never said that he wanted to use strings for small, medium, and large. You should just avoid answer questions like this one, because they are very broad and ambiguous.
@MoinuddinQuadri How do you know this? Did he tell you already?
@Mr.goosberry I do not know this, that is why I haven't answered anything. It is based on my assumption of variable name i.e. size
@Mr.goosberry Quote characters indicate strings, no?
@Yakuza Well it appears that you guessed right. But I only like to answer questions that I know can be concretely answered, and I don't have to guess about what the OP means.
|
6

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'

4 Comments

Can't you set size = 'tiny'?
yes but it would be a str. Given Python's duck typing you can set any variable to anything, so there is no formulation that would prevent such an assignment.
The question asks How can I explicitly define what values can [a] given variable have?. While enums are relevant, it doesn't seem like you can restrict in Python a general variable to have a limited set of values. Class fields are another matter.
In a strict sense you are correct, but in practice the use case OP describes is best handled in Python by the enum library. Even if you make size an instance of a class that restricts instance variable values (which is actually what you are doing by using enum, just doing it Pythonically), you can again just do size = 'tiny' and shed size's enumity
3

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.