movie rental

the great split debate

Filed under: Blogroll, django, fields, multiemailfield, newforms, python — Wrote by Otu on Wednesday, August 15th, 2007 @ 6:06 am

The django documentation for newforms gives an example of how to extend the forms.Field class here.

A snippet is shown below.

from django import newforms as forms

class MultiEmailField(forms.Field):
    def clean(self, value):
        emails = value.split(',')
        for email in emails:
            if not is_valid_email(email):
                raise forms.ValidationError('%s is not \
a valid e-mail address.' % email)
        if not emails:
            raise forms.ValidationError('Enter at least \
one e-mail address.')
        return emails

What is wrong with this code?

The variable value is always a string (an empy one “” if value is None).
The python#str split operation returns a list of either the substrings which make up the original or it returns a list with the original string in it if not split.

For instance

“boy girl cat”.split(” “) ==> [’boy’, ‘girl’, ‘cat’]

and

“boy girl cat”.split(”,”) ==> [”boy girl cat”]

Of course in the case where our original string is empty, the returned result is [”"].
Now, in python, you can use None, [], {} as the predicate in your if-else clause.

At this point in the code,

        if not emails:
            raise forms.Valid.......

The author of the above code intended to do so, but was thwarted as he is instead testing a predicate which will never be false.

The question that then arises is who is to blame?

The user: For failing to realise the behaviour of the python split function?

or

The language authors: Who should perhaps return as truly empty list [] not [”"] when split is called on an empty string?

Formation SAGE © il maestro ignoto