Jun 17 2011

[python] Verificador de documentos Uruguayos

Category: Pythontuxie @ 16:44

El siguiente script valida el número de cédula de identidad Uruguaya.


# -*- coding: utf-8 -*-
import re
import sys

CI_RE = re.compile(r'\d')
CI_MAGIC_NUMBERS = (4, 3, 6, 7, 8, 9, 2)

def check(ci):
_ci = CI_RE.findall(ci)
_ci.reverse()
counter = 0
for key, value in enumerate(_ci[1:]):
counter += int(value) * CI_MAGIC_NUMBERS[key]
counter %= 10
if (10 - counter) % 10 != int(_ci[0]):
return False
return True

if __name__ == '__main__':
if check(sys.argv[1]):
print('OK')
else:
print('ERROR')

Para utilizarlo correrlo de la siguiente forma:


$ python validarci.py 1.23456-1

Ver también: Script Numeros Cedula Uruguay.


Jun 11 2011

Avoiding circular imports

Category: Pythontuxie @ 14:47

Whenever you find yourself in a situation where two modules import each other, the easiest way out is to move one of the pieces of code to an external module. Example:

secret.py

from .models import User

def get_key():
return '53cr37 k3y'

def get_user_model():
return User

models.py

from .secret import get_key
from hashlib import sha256

class User(object):
"""A user.
"""

def __init__(self, username, password):
self.username = username
self.password = sha256('%s&&%s' % (password, get_key())).hexdigest()

You may argue that this example doesn’t make much sense, and I must agree, but describes well enough the problem.

As you can see in the previous code we have 2 modules, secret.py and models.py both importing code from each other. What you should do in this case is move one of the imported bits onto a new module, for example:

secret.py

def get_key():
return '53cr37 k3y'

users.py

from .models import User

def get_user_model():
return User

Now models.py imports from secret.py and the new file users.py imports from models.py, while secret.py doesn’t import code at all. It could be described as:

users < models < secret


Jun 11 2011

First post

Category: Uncategorizedtuxie @ 14:31

Past this point all you’ll find is an IndexError.