File: change.py

package info (click to toggle)
python-agate 1.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,996 kB
  • sloc: python: 8,512; makefile: 126
file content (65 lines) | stat: -rw-r--r-- 2,484 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from agate.aggregations.has_nulls import HasNulls
from agate.computations.base import Computation
from agate.data_types import Date, DateTime, Number, TimeDelta
from agate.exceptions import DataTypeError
from agate.warns import warn_null_calculation


class Change(Computation):
    """
    Calculate the difference between two columns.

    This calculation can be applied to :class:`.Number` columns to calculate
    numbers. It can also be applied to :class:`.Date`, :class:`.DateTime`, and
    :class:`.TimeDelta` columns to calculate time deltas.

    :param before_column_name:
        The name of a column containing the "before" values.
    :param after_column_name:
        The name of a column containing the "after" values.
    """
    def __init__(self, before_column_name, after_column_name):
        self._before_column_name = before_column_name
        self._after_column_name = after_column_name

    def get_computed_data_type(self, table):
        before_column = table.columns[self._before_column_name]

        if isinstance(before_column.data_type, (Date, DateTime, TimeDelta)):
            return TimeDelta()
        if isinstance(before_column.data_type, Number):
            return Number()

    def validate(self, table):
        before_column = table.columns[self._before_column_name]
        after_column = table.columns[self._after_column_name]

        for data_type in (Number, Date, DateTime, TimeDelta):
            if isinstance(before_column.data_type, data_type):
                if not isinstance(after_column.data_type, data_type):
                    raise DataTypeError('Specified columns must be of the same type')

                if HasNulls(self._before_column_name).run(table):
                    warn_null_calculation(self, before_column)

                if HasNulls(self._after_column_name).run(table):
                    warn_null_calculation(self, after_column)

                return

        raise DataTypeError('Change before and after columns must both contain data that is one of: '
                            'Number, Date, DateTime or TimeDelta.')

    def run(self, table):
        new_column = []

        for row in table.rows:
            before = row[self._before_column_name]
            after = row[self._after_column_name]

            if before is not None and after is not None:
                new_column.append(after - before)
            else:
                new_column.append(None)

        return new_column