在python中通过assert语句存在参数

时间:2016-11-13 11:22:36

标签: python function arguments assert

有没有办法通过assert语句来检查函数的参数是否存在?

def fractional(x) :
    assert x==None, "argument missing"    <---- is it possible here to check?
    assert type(x) == int, 'x must be integer'
    assert x > 0 , ' x must be positive '
    output = 1
    for i in range ( 1 , int(x)+1) :
        output = output*i
    assert output > 0 , 'output must be positive'
    return output 
y=3
fractional()   <----- argument missing

1 个答案:

答案 0 :(得分:1)

你不应该明确断言参数的存在。如果在调用函数时没有给出参数,你将得到类似的错误:

>>> def foo(x):
...     pass
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 1 argument (0 given)
>>>

如果你想确保参数的其他属性(你提到的只存在),你可以测试这些属性并在不满足时引发异常:

>>> def foo(x):
...    if not isinstance(x, str):
...        raise ValueError("argument must be a string!")
...
>>> foo(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in foo
ValueError: argument must be a string!
>>>