可以选择 2-3 个选项作为函数参数的 Pythonic 方式 [英] Pythonic way to have a choice of 2-3 options as an argument to a function
问题描述
我有一个 Python 函数,它需要许多参数,其中之一是要执行的模拟类型.例如,选项可以是solar"、view"或both".
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.
允许用户设置这些的 Pythonic 方式是什么?
What is a Pythonic way to allow the user to set these?
我可以看到各种选项:
使用字符串变量并检查它 - 所以它会是
func(a, b, c, type='solar')
在类中设置一些常量并使用func(a, b, c, type=classname.SOLAR)
Set some constants in the class and use func(a, b, c, type=classname.SOLAR)
如果只有两个选项(就像我的一些函数一样),通过使用类似 func(a, b, c, do_solar=False)
让它使用查看"选项.
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.
对 Pythonic 的做法有什么偏好(或其他想法)吗?
Any preferences (or other ideas) for Pythonic ways of doing this?
推荐答案
如果 Niklas 在 他的回答中提出的观点不成立,我会使用字符串参数.标准库中有使用类似参数的 Python 模块.例如 csv.reader()
.
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()
.
sim_func(a, b, c, sim_type='solar')
记住在函数内部给出一个合理的错误,这有助于人们在输入错误的时候解决问题.
Remember to give a reasonable error inside the function, that helps people out if they type in 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)
...
这篇关于可以选择 2-3 个选项作为函数参数的 Pythonic 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!