Snippet: assertiter

Este bichito lo uso bastante para validar estructuras de iterables en librerias

def assertiter(obj, itertype=None, length=None, content=None):
    """Valide content of iterable.
    
    @param obj: The iterable to validate.
    @param itertype: Specify the class of the itereable, otherwise is lookup 
                     if obj has '__iter__' attribute.
    @param length: The valid length of the iterable. If its None any length is 
                   valid.
    @param content: Type of the content of the iterable.
    
    """
    if itertype != None:
        assert isinstance(obj, itertype), 
               "obj must be instance of '%s', found '%s'" % (itertype.__name__,  type(obj).__name__)
    else:
        assert hasattr(obj, "__iter__"), "'%s' is not iterable" % str(obj)
        
    if length != None:
        assert isinstance(length, int), 
               "length must be instance of 'int', found '%s'" 
               % type(length).__name__
               
        assert len(obj) == length, 
               "'obj' length must be %i, found: %i" % (length, len(obj))
        
    if content != None:
        assert isinstance(content, (list, tuple)), "'content' is not iterable"
        
        for idx, c, ct in zip(range(len(obj)), obj, content):
            
            assert isinstance(c, ct), 
                   "Element on position %i must be instance of %s, found '%s'" 
                   % (idx, ct.__name__, type(c).__name__)
       
    return True

Uso:

def foo(lista):
    # valida que la lista sea de tipo list, de 3 elementos  y el primero
    # sea un int, el segundo un float y el tercero un string
    assert assertiter(lista, type=list length=3, content=[int, float, str])
    print "ok"

foo([1,2.0, "hola"]) # funciona
foo([1]) # falla, faltan 2 elementos
foo((1,2.0, "hola")) # falla es una tupla

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>