![](/img/trans.png)
[英]Best way to run a function in main function when one of the parameters is not in the scope
[英]Best way to ensure user to specify one and only one of the two function parameters in Python
在some_function
,我有两个参数freq
和frac
,我不希望用户同时指定它们,或者都不指定。 我希望他们仅指定其中之一。
这是工作代码:
def some_function(freq=False, frac=False):
if (freq is False) & (frac is False):
return (str(ValueError)+': Both freq and frac are not specified')
elif (freq is not False) & (frac is not False):
return (str(ValueError)+': Both freq and frac are specified')
elif (freq is not False) & (frac is False):
try:
print ('Do something')
except Exception as e:
print (e)
elif (freq is False) & (frac is not False):
try:
print ('Do something else')
except Exception as e:
print (e)
else: return (str(ValueError)+': Undetermined error')
是否有更好且更少冗长的实践来用Python表达这一点?
您可以在if
语句之前使用assert
。 您输入的类型不清楚; 通常,如果我知道这不是有效的输入,我将使用“ None
。
def some_function(freq=None, frac=None):
freq_flag = freq is not None
frac_flag = frac is not None
assert freq_flag + frac_flag == 1, "Specify exactly one of freq or frac"
if freq_flag:
print('Do something')
elif frac_flag:
print('Do something else')
您在这里做错了很多。 您可以测试not frac
而不是frac is False
,应该使用逻辑and
不是按位&
,并且应该引发那些ValueError
,而不返回它们:
def some_function(freq=False, frac=False):
if not freq and not frac:
raise ValueError('Both freq and frac are not specified')
elif freq and frac:
raise ValueError('Both freq and frac are specified')
elif freq:
print ('Do something')
else:
print ('Do something else')
通常,您正在寻找两个选项之一。 为什么不要求用户传递一个布尔值,如果True
则表示freq
,如果False
则表示frac
呢?
def some_function(freq):
if freq:
print ('Do something')
else:
print ('Do something else')
无效的简单pythonic解决方案:使用两个不同的函数(它们最终可能只是真正的一个门面):
__all__ = ["freqfunc", "fracfunc"]
# private implementation
def _somefunc(freq=False, frac=False):
# your code here
def freqfunc(freq):
return _somefunc(freq=freq)
def fraqfunc(frac):
return _somefunc(frac=frac)
现在可能会有更好的解决方案,但是如果没有更多细节就无法分辨...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.