简体   繁体   中英

How can I accept only some strings in Python function?

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.
Like, kind of like this:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM