Source code for pysqllike.generic.column_group_operator

# -*- coding: utf-8 -*-
"""
Creates custom classes to interpret Python expression as column operations.


:githublink:`%|py|6`
"""

from .column_operator import ColumnOperator
from .others_types import NA


[docs]class ColumnGroupOperator(ColumnOperator): """ Defines an operation between two columns. :githublink:`%|py|14` """
[docs] def __init__(self): """ Initiates the operator. :param name: name of the column :githublink:`%|py|21` """ pass
[docs] def __str__(self): """ usual :githublink:`%|py|27` """ raise NotImplementedError()
[docs] def __call__(self, columns): """ returns the results of this operation between a list of columns :githublink:`%|py|33` """ raise NotImplementedError()
[docs]class OperatorGroupLen(ColumnGroupOperator): """ defines the group function ``len`` :githublink:`%|py|41` """
[docs] def __str__(self): """ usual :githublink:`%|py|46` """ return "len"
[docs] def __call__(self, columns): """ returns the results of this operation between a list of columns :githublink:`%|py|52` """ if not hasattr(columns, '__iter__'): raise TypeError( "we expect an iterator here not " + str(type(columns))) return len(columns)
[docs]class OperatorGroupAvg(ColumnGroupOperator): """ defines the group function ``avg``, the default value when the set is empty is None :githublink:`%|py|63` """
[docs] def __str__(self): """ usual :githublink:`%|py|68` """ return "avg"
[docs] def __call__(self, columns): """ returns the results of this operation between a list of columns, it returns :class:`NA <pysqllike.generic.others_types.NA>` for a null set :githublink:`%|py|75` """ if not hasattr(columns, '__iter__'): raise TypeError( "we expect an iterator here not " + str(type(columns))) # we walk through the set only once nb = 0 for val in columns: if nb == 0: s = val else: s += val nb += 1 if nb == 0: return NA else: return s / nb