Home > Back-end >  How to correctly specify the type of the argument?
How to correctly specify the type of the argument?

Time:11-12

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related