I have a Python function which requires a number of parameters, one of which is the type of simulation to perform. For example, the options could be "solar", "view" or "both.
What is a Pythonic way to allow the user to set these?
I can see various options:
Use a string variable and check it - so it would be
func(a, b, c, type='solar')
Set some constants in the class and use
func(a, b, c, type=classname.SOLAR)
If there are only two options (as there are for some of my functions) force it into a True/False argument, by using something like
func(a, b, c, do_solar=False)
to get it to use the 'view' option.
Any preferences (or other ideas) for Pythonic ways of doing this?
Since functions are objects in python, you could actually process *args as a list of methods and pass the types of simulations as arbitratry args at the end. This would have the benefit of allowing you to define new simulations in the future without having to refactor this code.
Use:
Output:
You can use optional (keyword) arguments like this
If the point Niklas' makes in his answer doesn't hold, I would use a string argument. There are Python modules in the standard library that use similar arguments. For example
csv.reader()
.Remember to give a reasonable error inside the function, that helps people out if they type in the wrong thing.
I don't like any of those options.
I'd define two different functions,
perform_solar(a, b, c)
andperform_view(a, b, c)
and let the caller decide which ones he wants to use, in which order and with which arguments.If the reason why you thought you'd have to pack these into one single function is that they share state, you should share that state in an object and define the functions as methods.
You can use the assert statement like this:
If sim_types is not in the list, python will raise an Assertion Error