Skip to content
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
89a2c38
Add support and test for pd.Series
EkberHasanov Jun 25, 2023
b726b19
Adding docs for basic usage
EkberHasanov Jun 25, 2023
24bf87a
Fix documentation
EkberHasanov Jun 25, 2023
1bb8a71
Add pandas to optional dependencies
EkberHasanov Jun 25, 2023
bc37f7f
fix python3.8 issues
EkberHasanov Jun 26, 2023
43be7f6
fix py3.7 issues
EkberHasanov Jun 26, 2023
50b0547
fix macos error
EkberHasanov Jun 27, 2023
16aa656
fix indentation error in ci.yml
EkberHasanov Jun 27, 2023
0d899c9
ci: fix dependency issue in macos
EkberHasanov Jun 30, 2023
33f45f2
improve test coverage to 100%
EkberHasanov Jun 30, 2023
98e58d6
🔧 update code
yezz123 Jun 30, 2023
b4a35ac
🍱 update requirements
yezz123 Jun 30, 2023
1660ca7
Merge branch 'main' into type/pandas
yezz123 Jun 30, 2023
b1e04f0
🍱 Fix Requirements
yezz123 Jun 30, 2023
2ac57cd
🍱 Fix Requirements
yezz123 Jun 30, 2023
339c71b
.
yezz123 Jun 30, 2023
7129b91
fix
yezz123 Jun 30, 2023
c9c4f12
Update pydantic_extra_types/pandas_types.py
yezz123 Jul 1, 2023
cc9dac0
Inheriting directly from pd.Series
EkberHasanov Jul 6, 2023
501c173
Merge branch 'main' into type/pandas
EkberHasanov Jul 6, 2023
09e073d
delete extra files
EkberHasanov Jul 12, 2023
b15b3d0
upgrading version of pandas
EkberHasanov Feb 25, 2024
2718471
Merge branch 'main' into type/pandas
EkberHasanov Feb 25, 2024
8e408bc
Update pyproject.txt
EkberHasanov Feb 25, 2024
7b4433f
Update test_json_schema.py
EkberHasanov Feb 25, 2024
6cff2d7
Update linting.in
EkberHasanov Feb 25, 2024
3d7b805
adding pandas-stubs
EkberHasanov Feb 25, 2024
b751633
fix versions
EkberHasanov Feb 25, 2024
d78fc5a
resolve version issue
EkberHasanov Feb 25, 2024
6a55cd2
upgrading version of numpy
EkberHasanov Feb 25, 2024
ba7a941
fixing some issues
EkberHasanov Feb 25, 2024
933540a
change core_schema func
EkberHasanov Feb 29, 2024
25da211
Merge branch 'main' into type/pandas
EkberHasanov Feb 29, 2024
811d664
Update test_json_schema.py
EkberHasanov Feb 29, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,21 @@ jobs:
with:
python-version: ${{ matrix.python-version }}

- name: Install bzip2 on macOS
if: matrix.os == 'macos'
run: brew install bzip2


- name: Set environment variables
if: matrix.os == 'macos'
run: |
export LDFLAGS="-L/usr/local/opt/bzip2/lib"
export CPPFLAGS="-I/usr/local/opt/bzip2/include"

- run: |
pip install -r requirements/pyproject.txt && pip install -r requirements/testing.txt


- run: pip freeze

- run: make test
Expand Down
25 changes: 25 additions & 0 deletions docs/pandas_types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

The `Series` class provides support for working with pandas Series objects.

```py
import pandas as pd
from pydantic import BaseModel

from pydantic_extra_types.pandas_types import Series


class MyData(BaseModel):
numbers: Series


data = {"numbers": pd.Series([1, 2, 3, 4, 5])}
my_data = MyData(**data)

print(my_data.numbers)
# > 0 1
# > 1 2
# > 2 3
# > 3 4
# > 4 5
# > dtype: int64
```
49 changes: 49 additions & 0 deletions pydantic_extra_types/pandas_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from typing import Any, List, Tuple, Type, TypeVar, Union

from pydantic import GetCoreSchemaHandler
from pydantic_core import core_schema

try:
import pandas as pd
except ModuleNotFoundError: # pragma: no cover
raise RuntimeError(
'`PhoneNumber` requires "phonenumbers" to be installed. You can install it with "pip install phonenumbers"'
)

T = TypeVar('T', str, bytes, bool, int, float, complex, pd.Timestamp, pd.Timedelta, pd.Period)


class Series:
def __init__(self, value: Any) -> None:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this "value"? pd.Series accepts many arguments. 🤔

self.value = pd.Series(value)

@classmethod
def __get_pydantic_core_schema__(
cls, source: Type[Any], handler: GetCoreSchemaHandler
) -> core_schema.AfterValidatorFunctionSchema:
return core_schema.general_after_validator_function(
cls._validate,
core_schema.any_schema(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is the best we can do. Is it? A series should be an array of some type, and I guess we are able to get this type as well.

)

@classmethod
def _validate(cls, __input_value: Any, _: core_schema.ValidationInfo) -> 'Series':
if isinstance(__input_value, pd.Series):
return cls(__input_value)
return cls(pd.Series(__input_value))

def __repr__(self) -> str:
return repr(self.value)

def __getattr__(self, name: str) -> Any:
return getattr(self.value, name)

def __eq__(self, __value: object) -> bool:
return isinstance(__value, (pd.Series, Series))

def __add__(self, other: Union['Series', List[Any], Tuple[Any], T]) -> 'Series':
if isinstance(other, Series):
result_val = self.value + other.value
else:
result_val = self.value + other
return Series(result_val)
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,15 @@ classifiers = [
]
requires-python = '>=3.7'
dependencies = [
'pydantic>=2.0b3',
'pydantic>=2.0',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please open a new PR for this.

Suggested change
'pydantic>=2.0',
'pydantic>=2.0b3',

]
dynamic = ['version']

[project.optional-dependencies]
all = [
'phonenumbers>=8,<9',
'pycountry>=22,<23',
'pandas==1.3.5',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not pandas>=2.0?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because pandas>=2.0 requires python >=3.8

]

[project.urls]
Expand Down
1 change: 1 addition & 0 deletions requirements/linting.in
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ annotated-types
black
pyupgrade
ruff
pandas-stubs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likely not needed on pandas >= 2.

30 changes: 20 additions & 10 deletions requirements/linting.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#
# This file is autogenerated by pip-compile with Python 3.11
# This file is autogenerated by pip-compile with Python 3.10
# by the following command:
#
# pip-compile --output-file=requirements/linting.txt --resolver=backtracking requirements/linting.in
Expand All @@ -14,39 +14,49 @@ click==8.1.3
# via black
distlib==0.3.6
# via virtualenv
filelock==3.12.0
filelock==3.12.2
# via virtualenv
identify==2.5.24
# via pre-commit
mypy==1.3.0
mypy==1.4.1
# via -r requirements/linting.in
mypy-extensions==1.0.0
# via
# black
# mypy
nodeenv==1.8.0
# via pre-commit
numpy==1.25.0
# via pandas-stubs
packaging==23.1
# via black
pandas-stubs==2.0.2.230605
# via -r requirements/linting.in
pathspec==0.11.1
# via black
platformdirs==3.5.1
platformdirs==3.8.0
# via
# black
# virtualenv
pre-commit==3.3.2
pre-commit==3.3.3
# via -r requirements/linting.in
pyupgrade==3.4.0
pyupgrade==3.7.0
# via -r requirements/linting.in
pyyaml==6.0
# via pre-commit
ruff==0.0.270
ruff==0.0.275
# via -r requirements/linting.in
tokenize-rt==5.0.0
tokenize-rt==5.1.0
# via pyupgrade
typing-extensions==4.6.3
tomli==2.0.1
# via
# black
# mypy
types-pytz==2023.3.0.0
# via pandas-stubs
typing-extensions==4.7.0
# via mypy
virtualenv==20.23.0
virtualenv==20.23.1
# via pre-commit

# The following packages are considered to be unsafe in a requirements file:
Expand Down
16 changes: 10 additions & 6 deletions requirements/pyproject.txt
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
#
# This file is autogenerated by pip-compile with Python 3.11
# This file is autogenerated by pip-compile with Python 3.10
# by the following command:
#
# pip-compile --extra=all --output-file=requirements/pyproject.txt --resolver=backtracking pyproject.toml
#
annotated-types==0.5.0
# via pydantic
phonenumbers==8.13.13
pandas==1.3.5
# via pydantic-extra-types (pyproject.toml)
phonenumbers==8.13.15
# via pydantic-extra-types (pyproject.toml)
pycountry==22.3.5
# via pydantic-extra-types (pyproject.toml)
pydantic==2.0b2
pydantic==2.0
# via pydantic-extra-types (pyproject.toml)
pydantic-core==0.38.0
# via pydantic
typing-extensions==4.6.3
pydantic-core==2.0.1
# via pydantic
typing-extensions==4.7.0
# via
# pydantic
# pydantic-core

# The following packages are considered to be unsafe in a requirements file:
# setuptools
10 changes: 10 additions & 0 deletions tests/test_json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
CountryOfficialName,
CountryShortName,
)
from pydantic_extra_types.pandas_types import Series
from pydantic_extra_types.payment import PaymentCardNumber


Expand Down Expand Up @@ -85,6 +86,15 @@
'type': 'object',
},
),
(
Series,
{
'properties': {'x': {'title': 'X'}},
'required': ['x'],
'title': 'Model',
'type': 'object',
},
),
],
)
def test_json_schema(cls, expected):
Expand Down
115 changes: 115 additions & 0 deletions tests/test_pandas_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import pandas as pd
import pytest
from pydantic import BaseModel

from pydantic_extra_types.pandas_types import Series


@pytest.fixture(scope='session', name='SeriesModel')
def series_model_fixture():
class SeriesModel(BaseModel):
data: Series

return SeriesModel


@pytest.mark.parametrize(
'data, expected',
[
([1, 2, 3], [1, 2, 3]),
([], []),
([10, 20, 30, 40], [10, 20, 30, 40]),
],
)
def test_series_creation(data, expected):
if pd.__version__ <= '1.5.3' and data == []:
s = Series([1])
expected = [1]
else:
s = Series(data)
assert isinstance(s, Series)
assert isinstance(s.value, pd.Series)
assert s.value.tolist() == expected


def test_series_repr():
data = [1, 2, 3]
s = Series(data)
assert repr(s) == repr(pd.Series(data))


def test_series_attribute_access():
data = [1, 2, 3]
s = Series(data)
assert s.sum() == pd.Series(data).sum()


def test_series_equality():
data = [1, 2, 3]
s1 = Series(data)
s2 = Series(data)
assert s1 == s2
assert s2 == pd.Series(data)


def test_series_addition():
data1 = [1, 2, 3]
data2 = [4, 5, 6]
s1 = Series(data1)
s2 = Series(data2)
s3 = s1 + s2
assert isinstance(s3, Series)
assert s3.value.tolist() == [5, 7, 9]


@pytest.mark.parametrize(
'data, other, expected',
[
([1, 2, 3], [4, 5, 6], [5, 7, 9]),
([10, 20, 30], (1, 2, 3), [11, 22, 33]),
([5, 10, 15], pd.Series([1, 2, 3]), [6, 12, 18]),
],
)
def test_series_addition_with_types(data, other, expected):
s = Series(data)
result = s + other
assert isinstance(result, Series)
assert result.value.tolist() == expected


@pytest.mark.parametrize(
'data, other',
[
([1, 2, 3], 'invalid'), # Invalid type for addition
([1, 2, 3], {'a': 1, 'b': 2}), # Invalid type for addition
],
)
def test_series_addition_invalid_type_error(data, other) -> None:
s = Series(data)
with pytest.raises(TypeError):
s + other


@pytest.mark.parametrize(
'data, other',
[
([1, 2, 3], []),
],
)
def test_series_addition_invalid_value_error(data, other) -> None:
s = Series(data)
with pytest.raises(ValueError):
s + other


def test_valid_series_model(SeriesModel) -> None:
model = SeriesModel(data=[1, 2, 4])
assert isinstance(model.data, Series)
assert model.data == pd.Series([1, 2, 4])


def test_valid_series_model_with_pd_series(SeriesModel) -> None:
s = pd.Series([1, 2, 4])
model = SeriesModel(data=s)
assert isinstance(model.data, Series)
assert model.data == s