Skip to content

Instantly share code, notes, and snippets.

@jhbuhrman
Created December 5, 2018 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhbuhrman/bc8101bb26edaac0b2c701fd5e7ea68d to your computer and use it in GitHub Desktop.
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
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