Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit argument to specific values in python

Tags:

python

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?

like image 467
ninhenzo64 Avatar asked Mar 15 '14 00:03

ninhenzo64


People also ask

Can I call a function with less parameters in Python?

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.

What are the 4 types of arguments in Python?

5 Types of Arguments in Python Function Definition:positional arguments. arbitrary positional arguments. arbitrary keyword arguments.

How do you pass a positional argument in Python?

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.


1 Answers

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.

like image 150
jrennie Avatar answered Sep 28 '22 06:09

jrennie