Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pandera.api.dataframe.model.DataFrameModel has unexpected generic subclass behaviour #1764

Open
3 tasks done
adzcai opened this issue Jul 26, 2024 · 0 comments
Open
3 tasks done
Labels
bug Something isn't working

Comments

@adzcai
Copy link

adzcai commented Jul 26, 2024

Describe the bug

Typically in Python, when making a generic subclass of a generic type, you can provide TypeVars as the type arguments to the base type. (See mypy docs for details.) However, creating a generic subclass of pandera.api.dataframe.model.DataFrameModel doesn't work as expected, and trying to instantiate the generic subclass with concrete type arguments raises a ValueError.

  • I have checked that this issue has not already been reported.
  • I have confirmed this bug exists on the latest version of pandera.
  • (optional) I have confirmed this bug exists on the main branch of pandera.

Code Sample, a copy-pastable example

I've provided the expected Python behaviour alongside the current pandera behaviour.

from pandera.api.dataframe.model import DataFrameModel, TDataFrame, TSchema
from typing import Generic, TypeVar

class Foo(Generic[TDataFrame, TSchema]): ...

class Bar(Foo[TDataFrame, TSchema]): ...

class Schema(DataFrameModel[TDataFrame, TSchema]): ...

print(Bar.__parameters__)  # (~TDataFrame, ~TSchema)
print(Schema.__parameters__)  # ()

import pandas as pd
from pandera.api.pandas.container import DataFrameSchema

x: Bar[pd.DataFrame, DataFrameSchema]  # no error
y: Schema[pd.DataFrame, DataFrameSchema]  # ValueError: Expected 0 generic arguments but found 2

Expected behavior

I'd expect the generic subclass (Schema above) to behave like a generic type.

Desktop (please complete the following information):

  • OS: macOS
  • Browser: Safari
  • Version: 0.20.3

Additional context

For now, this can be resolved by explicitly adding Generic to the subclass's bases:

class Schema(DataFrameModel[TDataFrame, TSchema], Generic[TDataFrame, TSchema]): ...

But with typical Python generics, this shouldn't be necessary. My guess is that overriding __class_getitem__ source and returning a new type is different from what Python does. We should probably be returning a typing._GenericAlias:

type(Bar[pd.DataFrame, DataFrameSchema])  # typing._GenericAlias
@adzcai adzcai added the bug Something isn't working label Jul 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant