1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
   | >>> def checkType(types,*args):
	'''types <-- (type) or (list|tuple of types)
        args <-- arguments to check'''
	if type(types) in (list,tuple):
		if not all(any(type(x)==y for y in types)for x in args):
			raise TypeError
	else:
		if not all(type(x)==types for x in args):
			raise TypeError
 
 
>>> def test(a,b,c):
	checkType(int, a,b,c)
	print "Ok"
 
 
>>> test(1,"a",2)
 
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    test(1,"a",2)
  File "<pyshell#19>", line 2, in test
    checkType(int, a,b,c)
  File "<pyshell#17>", line 3, in checkType
    raise TypeError
TypeError
>>> def test(a,b,c):
	checkType((int,str), a,b,c)
	print "Ok"
 
>>> test(1,"a",2)
Ok
 
>>> def test2(a,b,c):
	checkType(int, a,b,c)
	print "Ok"
 
>>> test2(1,3,2)
Ok
>>> def test3(*a):
	checkType(int, *a)
	print "Ok"
 
 
>>> test3(1,'a')
 
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    test3(1,'a')
  File "<pyshell#33>", line 2, in test3
    checkType(int, *a)
  File "<pyshell#29>", line 5, in checkType
    raise TypeError
TypeError
>>> test3(1,2,3)
Ok | 
Partager