Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a data type able to hold only specific values

I have recently started with Python again, and I am trying to write a module where lots of problems of the following kind occur:

An object Problem can hold a variable Unit. Unit can only be either "inches", "millimeters" or "meters".

The module is supposed to be used by others, so I want the most easily usable solution to this. If possible I want the user to receive an error if they try to assign anything but one of those values.

I see this would be possible with objects where I define a unitClass class that inherits to daughter classes inchesClass, millimetersClass and metersClass. I would then make an instance of each, that the user can assign to the variable in question. But I think this might be confusing, unless that is a standard way to go about such a problem?

The other solution I came up with was set methods but since I don't use them for other variables, I wanted to avoid them in this case as well if possible.

Is there another way to do this using just the modules provided by a standard python installation?

Regards,

RTT

like image 522
Rikki-Tikki-Tavi Avatar asked Mar 11 '26 22:03

Rikki-Tikki-Tavi


1 Answers

In other languages (namely java), this kind of structure is called an enum or enumeration. Specifically because you enumerate the possible values for something.

In python 3, you can import enum and use it like so:

from enum import Enum

class Color(Enum):

    red = 1
    green = 2
    blue = 3

There's a post that goes more in depth here: How can I represent an 'Enum' in Python?

If you want an example of how to extend this to your specific case I'd do it like so, by creating a Unit enum:

class Unit(Enum):
    inches, millimeters, meters = range(3)

class Problem(object):

    def __init__(self, units):
        self.unit = getattr(Unit(), units) 
like image 60
Slater Victoroff Avatar answered Mar 14 '26 10:03

Slater Victoroff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!