How to validate the __init__ parameters
r0g
aioe.org at technicalbloke.com
Mon Dec 21 16:49:11 EST 2009
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
>
> All examples that I saw with property didn't show a way to do it in
> the __init__. Just to clarify, I don't want to check if the parameter
> is an int, or something like that, I want to know if the parameter do
> not use more than X chars; and want to do it when I'm 'creating' the
> instance; not after the creation:
>
> a = A('foo', 'bar')
>
> not
>
> class A:
> def __init__(self, foo = None, bar = None):
> self._foo = foo
> self._bar = bar
> def set_foo(self, foo):
> if len(foo) > 5:
> raise <something>
> _foo = foo
> foo = property(setter = set_foo)
>
> a = A()
> a.foo = 'foo'
>
>
> I thought in something like:
>
> class A:
> def __init__(self, foo = None, bar = None):
> set_foo(foo)
> self._bar = bar
> def set_foo(self, foo):
> if len(foo) > 5:
> raise <something>
> _foo = foo
> foo = property(setter = set_foo)
>
> But looks too much like java
I use assertions myself e.g.
>>> foo = "123456"
>>> assert len(foo) <= 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
Dunno if this would be considered good or bad programming practice by
those more experienced than I (comment always welcome!) but it works for
me :)
Roger.
More information about the Python-list
mailing list