If I have python function with a string argument which needs to be in a specific list of values, what's the best way to handle this? Is there a convention to expressing this in the docstrings or anything?
eg.
def makeShape(shape):
assert shape in ["circle", "square", "triangle"]
Is there a nicer way to express that shape should always be one of those three values?
You can call the function with or without the argument, and if there is no argument in the function call, then a default value is used.
5 Types of Arguments in Python Function Definition:positional arguments. arbitrary positional arguments. arbitrary keyword arguments.
Functions can accept a variable number of positional arguments by using *args in the def statement. You can use the items from a sequence as the positional arguments for a function with the * operator. Using the * operator with a generator may cause your program to run out of memory and crash.
If this is a genuine error, you should raise an exception. I think TypeError would be a reasonable choice, but you may want to define your own.
assert
statements are for development. Note that they are ignored when the -O
argument is used, so they should not be relied upon to catch errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With