Receita: Classe para lidar com CPF
Classe para lidar mais facilmente com CPF.
Código
1 class Cpf:
2 def __init__( self ):
3 """
4 Class to interact with CPF numbers
5 """
6 pass
7
8 def format( self, cpf ):
9 """
10 Method that formats a brazilian CPF
11
12 Tests:
13 >>> print Cpf().format('91289037736')
14 912.890.377-36
15 """
16 return "%s.%s.%s-%s" % ( cpf[0:3], cpf[3:6], cpf[6:9], cpf[9:11] )
17
18 def validate( self, cpf ):
19 """
20 Method to validate a brazilian CPF number
21 Based on Pedro Werneck source avaiable at
22 www.PythonBrasil.com.br
23
24 Tests:
25 >>> print Cpf().validate('91289037736')
26 True
27 >>> print Cpf().validate('91289037731')
28 False
29 """
30 cpf_invalidos = [11*str(i) for i in range(10)]
31 if cpf in cpf_invalidos:
32 return False
33
34 if not cpf.isdigit():
35 """ Verifica se o CPF contem pontos e hifens """
36 cpf = cpf.replace( ".", "" )
37 cpf = cpf.replace( "-", "" )
38
39 if len( cpf ) < 11:
40 """ Verifica se o CPF tem 11 digitos """
41 return False
42
43 if len( cpf ) > 11:
44 """ CPF tem que ter 11 digitos """
45 return False
46
47 selfcpf = [int( x ) for x in cpf]
48
49 cpf = selfcpf[:9]
50
51 while len( cpf ) < 11:
52
53 r = sum( [( len( cpf )+1-i )*v for i, v in [( x, cpf[x] ) for x in range( len( cpf ) )]] ) % 11
54
55 if r > 1:
56 f = 11 - r
57 else:
58 f = 0
59 cpf.append( f )
60
61
62 return bool( cpf == selfcpf )
63
64 # test
65 #import doctest ; doctest.testmod()
Exemplo de uso
Dentro do próprio código. Nas docstrings.
Volta para CookBook.
Murtog