Column names and types of pandas.Dataframe with mypy or other static way?

Viewed 278

I have a function func which accepts a pandas.Dataframe, The dataframe must have the columns: 'col_foo', 'col_bar' and their types must be pd.Timestamp, np.integer for func to no fail.

how would I ensure these columns exist in a static manner?


I can do something like this:

def func(df: pd.Dataframe):
    cols_struct = {'col_foo': pd.Timestamp, 'col_bar': np.integer}
    # also check the columns types here
    if not set(df.columns).issuperset(cols_struct.keys()):
        raise ValueError('the dataframe must be structured like', cols_struct)
    

Or use an existing library and do it neatly with a decorator.

However I want my code to fail during mypy static type check and not during runtime, How would I type hint func?

0 Answers
Related