How to correctly specify the type of the argument?

Question:

I have a ButtonTypes class:

class ButtonTypes:
    def __init__(self):
        self.textType = "text"
        self.callbackType = "callback"
        self.locationType = "location"
        self.someAnotherType = "someAnotherType"

And a function that should take one of the attributes of the ButtonTypes class as an argument:

def create_button(button_type):
    pass

How can I specify that the argument of the create_button function should not just be a string, but exactly one of the attributes of the ButtonTypes class?

Something like this:
def create_button(button_type: ButtonTypes.Type)

As far as I understand, I need to create a Type class inside the ButtonTypes class, and then many other classes for each type that inherit the Type class, but I think something in my train of thought is wrong.

Asked By: Mus1k

||

Answers:

Use an enumerated type.

from enum import Enum

class ButtonType:
    TEXT = "text"
    CALLBACK = "callback"
    LOCATION = "location"
    SOMETHINGELSE = "someOtherType"


def create_button(button_type: ButtonType):
    ...

This goes one step further: not only are there only 4 values of type ButtonType, but no string will work, even at runtime, since your function will either ignore the string value associated with the ButtonType value altogether, or use code to extract the string that will break if button_type is an arbitrary string.

Answered By: chepner

It sounds like you actually want an Enum:

from enum import Enum

class ButtonTypes(Enum):
    textType = "text"
    callbackType = "callback"
    locationType = "location"
    someAnotherType = "someAnotherType"

def func(button_type: ButtonTypes):
    # Use button_type

The enum specifies a closed set of options that the variable must be a part of.

Answered By: Carcigenicate
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.