How to validate the __init__ parameters

Alf P. Steinbach alfps at start.no
Mon Dec 21 13:07:10 EST 2009


* Denis Doria:
> 
> 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

Yeah.

If member _foo has this constraint regardless then it's logically part of that 
member's type, so make it a type:

   class _Foo:
     def __init__( self, seq ):
       if seq is None:
         self.items = []
       elif len( seq ) > 5:
         raise <something>
       else:
         self.items = seq

   class A:  # Your example
     def __init__( self, foo = None, Bar = None ):
       self._foo = _Foo( foo )
       self._bar = bar
     def set_foo( self, foo ):
       self._foo = _Foo( foo )
     foo = property( setter = set_foo )


Cheers & hth.,

- Alf



More information about the Python-list mailing list