5

I want to make it like this:

>>> myfunc("strawberry")
ok
# myfunc only works with strawberry

I know that most people will answer with:

def myfunc(something):
    if something == "strawberry":
        print("ok")

But I want to do all this in the parameter setting.

Kind of like this:

def myfunc(something: OnlyThese["strawberry", "cake"]):
    print("ok")

Although the code above is incorrect, I want to see if Python already has a feature like this.

3

2 Answers 2

5

Sound like you are looking for enum. If you are using Python 3.11 or later, there's the StrEnum class:

from enum import StrEnum

class Something(StrEnum):
    strawberry = "strawberry"
    cake = "cake"

def myfunc(something: Something):
    something = Something(something)
    print(something)

# OK
myfunc(Something.strawberry)
myfunc("cake")

# ValueError
myfunc("blackberry")

Inside your function something is a subclass of str so it can be treated as a string almost every where.

Sign up to request clarification or add additional context in comments.

2 Comments

Suppose I want a function argument to be only "float32" or "float64", is StrEnum the best practice? Thks
@RémyHosseinkhanBoucher this is the internal coding standard at my company. I can't find any authority sources for this practice so I'm a little reluctant to call it best practice but it's a good one IMO.
1

Don't believe there is a way to do what you are wanting to do without writing code in the function body.

I found answers to a similar question at

enforce arguments to a specific list of values

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.