The pythonic way of choosing 2-3 options as a function argument

I have a Python function that requires several parameters, one of which is the type of simulation to execute. For example, the options may be β€œsunny,” β€œview,” or β€œboth.”

What is Pythonic to allow the user to install them?

I see various options:

  • Use a string variable and check it - so it will be func(a, b, c, type='solar')

  • Define some constants in the class and use func(a, b, c, type=classname.SOLAR)

  • If there are only two options (as for some of my functions), force it into the True / False argument, using something like func(a, b, c, do_solar=False) to force it to use the "view" option .

Any preferences (or other ideas) for pythonic ways to do this?

+6
source share
4 answers

I do not like any of these options.

I would define two different functions: perform_solar(a, b, c) and perform_view(a, b, c) and call the caller which ones he wants to use, in which order and with what arguments.

If the reason you thought you would have to pack them into one single function is because they share the state, you should share that state in the object and define the functions as methods.

+3
source

If Niklas' point does in its answer is not satisfied, I would use a string argument. The standard library has Python modules that use similar arguments. For example csv.reader() .

 sim_func(a, b, c, sim_type='solar') 

Remember to give a reasonable error inside a function that helps people if they introduce the wrong thing.

 def sim_func(a, b, c, sim_type='solar'): sim_types = ['solar', 'view', 'both'] if sim_type not in sim_types: raise ValueError("Invalid sim type. Expected one of: %s" % sim_types) ... 
+3
source

Since functions are objects in python, you can actually treat * args as a list of methods and pass modeling types as args arguments at the end. This would allow you to define new simulations in the future without the need to reorganize this code.

 def func(a, b, c, *args): for arg in args: arg(a, b, c) def foosim(a, b, c): print 'foosim %d' % (a + b + c) def barsim(a, b, c): print 'barsim %d' % (a * b * c) 

Using:

 func(2, 2, 3, foosim) func(2, 2, 3, barsim) func(2, 2, 3, foosim, barsim) 

Conclusion:

 foosim 7 barsim 12 foosim 7 barsim 12 
+2
source

You can use optional (keywords) arguments like this

 def func(a, b, c, **kw): if kw.get('do_solar'): # Do Solar if kw.get('do_view'): # Do view 
+1
source

Source: https://habr.com/ru/post/909775/


All Articles