将多个变量断言为同一类型

Asserting several variables as same type

问题: 我有一个接受参数 nbase 的函数,我想确保这两个参数都是事实上整数。到目前为止,我已经完成了以下工作:

#  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(nbase 都是 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

没有矢量化 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))