tags:

views:

79

answers:

4

Having a simple Python class like this:

class Spam(object):
    __init__(self, description, value):
        self.description = description
        self.value = value

Which is the correct approach to check these constraints:

  • "description cannot be empty"
  • "value must be greater than zero"

Should i:
1. validate data before creating spam object ?
2. check data on __init__ method ?
3. create an is_valid method on Spam class and call it with spam.isValid() ?
4. create an is_valid static method on Spam class and call it with Spam.isValid(description, value) ?
5. check data on setters declaration ?
6. etc.

Could you recommend a well designed\Pythonic\not verbose (on class with many attributes)\elegant approach?

+7  A: 

You can use Python properties to cleanly apply rules to each field separately, and enforce them even when client code tries to change the field:

class Spam(object):
    def __init__(self, description, value):
        self.description = description
        self.value = value

    @property
    def description(self):
        return self._description

    @description.setter
    def description(self, d):
        if not d: raise Exception("description cannot be empty")
        self._description = d

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, v):
        if not (v > 0): raise Exception("value must be greater than zero")
        self._value = v

An exception will be thrown on any attempt to violate the rules, even in the __init__ function, in which case object construction will fail.

Marcelo Cantos
@Marcelo +1 elegant solution thanks, dont' you think is a little bit verbose for a small class like that?
systempuntoout
Agreed, it isn't the prettiest solution. Python prefers free-range classes (think chickens), and the idea of properties controlling access was a bit of an afterthought. Having said that, this wouldn't be much more concise in any other language I can think of.
Marcelo Cantos
+1  A: 

if you want to only validate those values passed to the constructor, you could do:

class Spam(object):
    def __init__(self, description, value):
        if not description or value <=0:
            raise ValueError
        self.description = description
        self.value = value

This will of course will not prevent anyone from doing something like this:

>>> s = Spam('s', 5)
>>> s.value = 0
>>> s.value
0

So, correct approach depends on what you're trying to accomplish.

SilentGhost
@SilentGhost this is my actual approach; but i don't like it when attributes number raise and\or constraints checks are more sophisticated.It seems to clutter the init method too much.
systempuntoout
@system: you can separate validity check into its own method: there are not hard and fast rules about this situation.
SilentGhost
+1  A: 

If you only want to validate the values when the object is created AND passing in invalid values is considered a programming error then I would use assertions:

class Spam(object):
    __init__(self, description, value):
        assert description != ""
        assert value > 0
        self.description = description
        self.value = value

This is about as concise as you are going to get, and clearly documents that these are preconditions for creating the object.

Dave Kirby
@Dave thanks Dave, using assert, how do i specify to the client of that class what went wrong (description or value)? Don't you think that assertion should be used just to test conditions that should never happen?
systempuntoout
You can add a message to the assert statement e.g `assert value > 0, "value attribute to Spam must be greater than zero"`.Assertions are really messages to the developer and should not be caught by client code, since they indicate a programming error. If you want the client to catch and handle the error then explicitly raise an exception such as ValueError, as shown in the other answers.
Dave Kirby
To answer your second question, yes asserts should be used to test conditions that should never happen - that is why I said "if passing in invalid values is considered a programming error...". If that is not the case then don't use asserts.
Dave Kirby
+1  A: 

Unless you're hellbent on rolling your own, you can simply use formencode. It really shines with many attributes and schemas (just subclass schemas) and has a lot of useful validators builtin. As you can see this is the "validate data before creating spam object" approach.

from formencode import Schema, validators

class SpamSchema(Schema):
    description = validators.String(not_empty=True)
    value = validators.Int(min=0)

class Spam(object):
    def __init__(self, description, value):
        self.description = description
        self.value = value

## how you actually validate depends on your application
def validate_input( cls, schema, **input):
    data = schema.to_python(input) # validate `input` dict with the schema
    return cls(**data) # it validated here, else there was an exception

# returns a Spam object
validate_input( Spam, SpamSchema, description='this works', value=5) 

# raises an exception with all the invalid fields
validate_input( Spam, SpamSchema, description='', value=-1) 

You could do the checks during __init__ too (and make them completely transparent with descriptors|decorators|metaclass), but I'm not a big fan of that. I like a clean barrier between user input and internal objects.

THC4k