2

我想在不定义函数的情况下执行以下操作:

if isinstance(x,(list,tuple)) and every_element_isinstance(x,basestring):
   foobar

IE:implementing type checking

有速记/builtin这个吗?

4

4 回答 4

9

我认为这是最好的解决方案(如果我理解这个问题)

if isinstance(x, (list, tuple)) and all(isinstance(i, basestring) for i in x):
    #do whatever
于 2013-01-06T11:54:31.407 回答
5
if isinstance(x, (list, tuple)) and all([isinstance(i, basestring) for i in x]):
    foobar

令人惊讶的是,这里的列表理解[ ... ]比没有的更快,无论是短列表还是长列表:

短名单:

>>> timeit('isinstance(x, (list, tuple)) and all(isinstance(i, basestring) for i in x)', "x=['a','b','c']")
2.7594685942680144
>>> timeit('isinstance(x, (list, tuple)) and all(isinstance(i, basestring) for i in x)', "x=['a','b','c']")
2.8013695153947538
>>> timeit('isinstance(x, (list, tuple)) and all([isinstance(i, basestring) for i in x])', "x=['a','b','c']")
2.4351678506033068
>>> timeit('isinstance(x, (list, tuple)) and all([isinstance(i, basestring) for i in x])', "x=['a','b','c']")
2.4491469896721583

长名单:

>>> timeit('isinstance(x, (list, tuple)) and all(isinstance(i, basestring) for i in x)', "x=['a','b','c'] * 1000", number=1000)
1.3357901657891489
>>> timeit('isinstance(x, (list, tuple)) and all(isinstance(i, basestring) for i in x)', "x=['a','b','c'] * 1000", number=1000)
1.3305278872818462
>>> timeit('isinstance(x, (list, tuple)) and all([isinstance(i, basestring) for i in x])', "x=['a','b','c'] * 1000", number=1000)
1.2626525921055531
>>> timeit('isinstance(x, (list, tuple)) and all([isinstance(i, basestring) for i in x])', "x=['a','b','c'] * 1000", number=1000)
1.2881240045551863
于 2013-01-06T11:54:15.883 回答
5

没有内置定义泛型类型。但是有很多验证库可以模仿这个功能。

使用https://github.com/alectomas/voluptuous的示例:

>>> from voluptuous import Schema
>>> s_list = Schema([basestring]) # only strings in a list are allowed
>>> s_list("hello") 
...
voluptuous.InvalidList: expected a list
>>> s_list([123])
...
voluptuous.InvalidList: invalid list value @ data[0]
>>> s_list(["correct"])
["correct"] # returns the object, if validation was successful

前几天,这个库增加了对元组的支持:

>>> s_tuple = voluptuous.Schema((basestring, ))

现在将两者结合起来得到你的结果:

>>> from voluptuous import any

# - this is now equivalent to your code
# - raises Exceptions on invalid input
>>> schema = Schema(any(s_list, s_tuple))

甚至比 double- 还要快一点isinstance

>>> from timeit import timeit

>>> timeit('(schema(i) for i in x)', "x=['a','b','c']")
0.679318904876709

>>> timeit("""
        (isinstance(x, (list, tuple)) 
         and all(isinstance(i, basestring)) for i in x)""", "x=['a','b','c']")
0.7801780700683594
于 2013-01-06T11:54:41.957 回答
0

使用 voluptuous '0.8.7' 您可以从miku更新答案并跳过“元组部分”:

>>> from voluptuous import Schema
>>> from timeit import timeit
>>> s_list = Schema([basestring]) # only strings in a list are allowed
>>> timeit('(s_list(i) for i in x)', "x=['a','b','c']")
0.503572940826416
>>> timeit("(isinstance(x, (list, tuple)) and all(isinstance(i, basestring)) for i in x)", "x=['a','b','c']")
0.5400209426879883
于 2015-11-16T16:57:16.423 回答