On 12/22/2009 4:41 AM, Denis Doria wrote:
Hi;

I'm checking the best way to validate attributes inside a class. Of
course I can use property to check it, but I really want to do it
inside the __init__:

class A:
     def __init__(self, foo, bar):
         self.foo = foo #check if foo is correct
         self.bar = bar


A nice sugar to do that:

import functools

class CheckError(Exception): pass

def func_check(*argcheckers):
    def _checked(func):
        def _function(*args):
res = [(check(arg), check, arg) for check, arg in zip(argcheckers, args)]
            if all(r[0] for r in res):
                return func(*args)
            else:
                raise CheckError(filter(lambda x: x[0] == False, res))
        return _function
    return _checked

method_check = functools.partial(func_check, lambda a: True)

##########################################################
def check_foo(arg):
    return 5 <= arg <= 10

def check_bar(arg):
    return 10 <= arg < 20

class A(object):
    @method_check(check_foo, check_bar)
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to