associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

Revisão 1e 2005-10-16 22:45:09

Excluir mensagem

Cpf

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 
  31         if not cpf.isdigit():
  32             """ Verifica se o CPF contem pontos e hifens """
  33             cpf = cpf.replace( ".", "" )
  34             cpf = cpf.replace( "-", "" )
  35 
  36         if len( cpf ) < 11:
  37             """ Verifica se o CPF tem 11 digitos """
  38             return False
  39             
  40         if len( cpf ) > 11:
  41             """ CPF tem que ter 11 digitos """
  42             return False
  43             
  44         selfcpf = [int( x ) for x in cpf]
  45         
  46         cpf = selfcpf[:9]
  47         
  48         while len( cpf ) < 11:
  49         
  50             r =  sum( [( len( cpf )+1-i )*v for i, v in [( x, cpf[x] ) for x in range( len( cpf ) )]] ) % 11
  51         
  52             if r > 1:
  53                 f = 11 - r
  54             else:
  55                 f = 0
  56             cpf.append( f )
  57         
  58         
  59         return bool( cpf == selfcpf )
  60 
  61 # test
  62 #import doctest ; doctest.testmod()

Exemplo de uso

Dentro do próprio código. Nas docstrings.

Volta para CookBook.


Murtog