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

Python 将多个变量断言为同一类型,python,assertion,isinstance,Python,Assertion,Isinstance,问题:我有一个函数,它接受参数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}'.forma

问题:我有一个函数,它接受参数
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)
问题:这似乎很乏味,我想做一些类似于
断言isinstance((n,base),(int,int)),n和base必须是整数的事情。n:{0},基:{1}。格式(n,基)
。但是这在意外的时候给了我一个断言错误(
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

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

非常感谢。也许有一种更简单的方法可以做到这一点?对于一些变量,它工作得很好,但我想你可以有很多。我猜它可以在for循环中处理。另一方面,bool断言并不是多余的。如果没有它,pascal(True)将返回{1:[1]},这没有任何意义。您错了,
bool
的检查不是多余的,因为
bool
int
的子类。现在,它是否值得检查是有争议的,因为它确实是一个
int
,它不会破坏任何东西。当你这么做的时候,你有很多多余的括号。@MarkRansom我知道,对不起。我来自Lisp、Java和Haskell,刚刚学习Python。@RoyM没有必要检查
bool
,因为它们是
int
s,会按照预期的方式运行
pascal(True)
将返回
{1:[1]}
,这是有意义的。这正是您对pascal(1)的期望。