Jul 16 2011

Moving methods from one class to another

Category: Pythontuxie @ 16:23

Not too often you need to move a method from one class to another, but sometimes you just do. You may be tempted to do something like this:

>>> class A(object):
... def b(self):
... print('b')
>>> A.b

>>> class B(object):
... pass
>>> B.b = A.b
>>> B.b

>>> b = B()
>>> b.b

>>> b.b()
Traceback (most recent call last):
File "", line 1, in
TypeError: unbound method b() must be called with A instance as first argument (got nothing instead)

But as noted, it doesn’t work. In python even functions are objects, and A.b is an instance of your method. What you need is the class itself, the “raw” function:

>>> B.b = A.b.__func__
>>> B.b

>>> b.b()


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)
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]):

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:


from .models import User

def get_key():
return '53cr37 k3y'

def get_user_model():
return User


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:


def get_key():
return '53cr37 k3y'


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