2.2 The schema

If we define a schema we will be able to load not byte strings, but values with a type (integers, booleans, etc.). We do so by sub-classing:

    from itools.datatypes import Integer, Unicode, String, Date

    class Clients(CSVFile):

        columns = ['client_id', 'name', 'email',
            'registration_date']

        schema = {
            'client_id': Integer,
            'name': Unicode,
            'email': String,
            'registration_date': Date}

Now, if we load the CSV file with our new shinny class, we will be able to get values with a type, and to do other nice things:

    >>> clients = Clients('clients.csv')
    >>>
    >>> row = clients.get_row(0)
    >>> row
    [1, u'Piotr Macuk', 'piotr@macuk.pl',
     datetime.date(2004, 11, 09)]
    # Access a column by its name
    >>> print row.get_value('name')
    Piotr Macuk
    # Now 'update_row' expects the values to be of the good type
    >>> from datetime import date
    >>>
    >>> clients.update_row(0, registration_date=date(2004, 11, 10))
    # So is for the 'add_row' method
    >>> clients.add_row(
    ...     [250, u'J. David Ibanez', 'jdavid@itaapy.com',
    ...      date(2007, 1, 1)])

As we have seen the schema is defined with the class variable columns, which gives a name to each column, and with the class variable schema, which defines the type.