Created
December 5, 2018 08:44
-
-
Save jhbuhrman/bc8101bb26edaac0b2c701fd5e7ea68d to your computer and use it in GitHub Desktop.
Custom attrib validator with its info in the doc string of the containing attrs class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from typing import List | |
import attr | |
import pandas as pd | |
_log = logging.getLogger(__name__) | |
@attr.s(auto_attribs=True, repr=False, slots=True, hash=True) | |
class _HasColumnsValidator: | |
"""Class implementing the column_validator functionality. | |
The following attribute instance variables are defined:""" | |
columns: List[str] | |
__doc__ += """ | |
"ivar columns: the list of column names to check for""" | |
# Sentinel | |
__doc__ += """ | |
""" | |
def __call__(self, inst, attr, value: pd.DataFrame): | |
""""Perform the actual column check.""" | |
df_columns = value.columns.tolist() | |
if df_columns != self.columns: | |
df_columns_set = set(df_columns) | |
self_columns_set = set(self.columns) | |
raise ValueError( | |
f'attribute {attr.name!r} has columns {df_columns}, while' | |
f' it should have {self.columns}' | |
f' (missing: {self_columns_set - df_columns_set},' | |
f' extraneous {df_columns_set - self_columns_set})') | |
def __repr__(self): | |
return f'<has_columns validator for columns {self.columns}>' | |
def has_columns(columns: List[str]): | |
"""A validator suitable for use in attrs that raises a :exc:`ValueError` | |
if the initializer is called with a Pandas data frame with a different | |
list of columns as specified. | |
:param columns: The list of column names to check for. | |
:raises ValueError: With a human readable error message, including the | |
actual columns, the expected list of column names, the missing, and | |
extraneous column names. | |
""" | |
return _HasColumnsValidator(columns) | |
@attr.s(auto_attribs=True, frozen=True) | |
class InputDataFrames: | |
"""Collection of input (Pandas) data frames. | |
The following attribute instance variables are defined:""" | |
extension: pd.DataFrame = attr.ib(validator=has_columns(['foo', 'bar'])) | |
# extension: pd.DataFrame = attr.ib() | |
__doc__ += f""" | |
:ivar extension: Pandas data frame with columns | |
{extension.validator.__self__._validator.columns}""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment