问题:我有一个函数接受参数n
和base
,并且我想确保这两个参数实际上都是整数。到目前为止,我已经完成了以下操作:
# Conditions in which the function makes sense.
assert isinstance(n, (int)), 'n must be an integer. n: {0}'.format(n)
assert isinstance(base, (int)), 'base must be an integer. base: {0}'.format(base)
assert not isinstance(n, bool)
问题:这似乎很乏味,我想以某种方式做类似于assert isinstance((n, base), (int, int)), 'n and base must be integers. n: {0}, base: {1}'.format(n, base)
的事情。但这在意外的时间给了我一个AssertionError(n
和base
都是int)。也许不能使用元组?有一种可行的类似方法吗?
编辑:我想一种理想的处理方法是列出应该为t类型的每个参数,如果一个或多个失败,则仅打印出失败的那些参数。
为完整起见,请参见以下完整代码。我认为这不会有用,但我可能会误会。它不算什么,在这里看了另一个问题之后,我只是在随意使用可选参数。
def pascal(n, base=1):
"""Makes a dictionary where the keys are row-indexes in a pascal-trangle
of size n, and the values are the rows as a list. E.g. pascal(3) should
return {1 : [1], 2: [1,1], 3: [1,2,1]}.
pascal(0) should returns an empty dictionary.
Optional argument 'base=': set an integer as a new base. E.g.
pascal(3, base=2) should return {1: [2], 2: [2, 2], 3: [2, 4, 2]}"""
# Conditions in which the function makes sense.
# assert isinstance((n, base), (int, int)), 'n and base must be integers. n: {0}, base: {1}'.format(n, base)
assert isinstance(n, (int)), 'n must be an integer. n: {0}'.format(n)
assert isinstance(base, (int)), 'base must be an integer. base: {0}'.format(base)
assert not isinstance(n, bool)
if not n:
return {}
if n == 1:
return {1: [base]} # The basic case.
else:
bottom_row = list()
prev_p = pascal(n-1, base) # Only do one recursive call!
for i in range(0, n):
if i == 0:
bottom_row.append(prev_p[n-1][i])
elif i == n-1:
bottom_row.append(prev_p[n-1][i-1])
else:
bottom_row.append(prev_p[n-1][i-1]+prev_p[n-1][i])
bottom_row = {n: bottom_row}
pascal_dict = prev_p
pascal_dict.update(bottom_row)
return pascal_dict
答案 0 :(得分:3)
没有向量化的isinstance
。
assert isinstance((n, base), (int, int))
应该是
assert isinstance(n, int) and isinstance(base, int)
如果您有更多的变量...
for var in [n, base, count, blah, foo, bar]:
assert isinstance(var, int)
如果您不需要对其进行个别维修:
assert(all(isinstance(var, int) for var in list))