Skip to content

Make TzInfo picklable #770

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

Merged
merged 8 commits into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 9 additions & 0 deletions python/pydantic_core/_pydantic_core.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import datetime
import decimal
import sys
from typing import Any, Callable, Generic, Optional, Type, TypeVar
Expand Down Expand Up @@ -43,6 +44,7 @@ __all__ = [
'to_json',
'to_jsonable_python',
'list_all_errors',
'TzInfo',
]
__version__: str
build_profile: str
Expand Down Expand Up @@ -323,3 +325,10 @@ def list_all_errors() -> list[ErrorTypeInfo]:
"""
Get information about all built-in errors.
"""

@final
class TzInfo(datetime.tzinfo):
def tzname(self, _dt: datetime.datetime | None) -> str | None: ...
def utcoffset(self, _dt: datetime.datetime | None) -> datetime.timedelta: ...
def dst(self, _dt: datetime.datetime | None) -> datetime.timedelta: ...
def __deepcopy__(self, _memo: dict[Any, Any]) -> 'TzInfo': ...
10 changes: 9 additions & 1 deletion src/input/datetime.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use pyo3::intern;
use pyo3::prelude::*;

use pyo3::types::{PyDate, PyDateTime, PyDelta, PyDeltaAccess, PyDict, PyTime, PyTzInfo};
use speedate::MicrosecondsPrecisionOverflowBehavior;
use speedate::{Date, DateTime, Duration, ParseError, Time, TimeConfig};
use std::borrow::Cow;

use strum::EnumMessage;

use crate::errors::{ErrorType, ValError, ValResult};
Expand Down Expand Up @@ -447,7 +449,7 @@ pub fn float_as_duration<'a>(input: &'a impl Input<'a>, total_seconds: f64) -> V
#[pyclass(module = "pydantic_core._pydantic_core", extends = PyTzInfo)]
#[derive(Clone)]
#[cfg_attr(debug_assertions, derive(Debug))]
struct TzInfo {
pub struct TzInfo {
seconds: i32,
}

Expand Down Expand Up @@ -486,4 +488,10 @@ impl TzInfo {
fn __deepcopy__(&self, py: Python, _memo: &PyDict) -> PyResult<Py<Self>> {
Py::new(py, self.clone())
}

pub fn __reduce__(&self, py: Python) -> PyResult<PyObject> {
let args = (self.seconds,);
let cls = Py::new(py, self.clone())?.getattr(py, "__class__")?;
Ok((cls, args).into_py(py))
}
}
1 change: 1 addition & 0 deletions src/input/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod parse_json;
mod return_enums;
mod shared;

pub use datetime::TzInfo;
pub(crate) use datetime::{
duration_as_pytimedelta, pydate_as_date, pydatetime_as_datetime, pytime_as_time, pytimedelta_as_duration,
EitherDate, EitherDateTime, EitherTime, EitherTimedelta,
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ mod url;
mod validators;

// required for benchmarks
pub use self::input::TzInfo;
pub use self::url::{PyMultiHostUrl, PyUrl};
pub use argument_markers::{ArgsKwargs, PydanticUndefinedType};
pub use build_tools::SchemaError;
Expand Down Expand Up @@ -93,6 +94,7 @@ fn _pydantic_core(py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<PyMultiHostUrl>()?;
m.add_class::<ArgsKwargs>()?;
m.add_class::<SchemaSerializer>()?;
m.add_class::<TzInfo>()?;
Copy link
Member

Choose a reason for hiding this comment

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

does this actually need to be exported? If it does, we should have a test for importing it.

Copy link
Member Author

Choose a reason for hiding this comment

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

It does so that it can be unpickled

Copy link
Member Author

Choose a reason for hiding this comment

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

The pickle test is already testing that it can be imported

m.add_function(wrap_pyfunction!(to_json, m)?)?;
m.add_function(wrap_pyfunction!(to_jsonable_python, m)?)?;
m.add_function(wrap_pyfunction!(list_all_errors, m)?)?;
Expand Down
37 changes: 37 additions & 0 deletions tests/validators/test_datetime.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import copy
import json
import pickle
import platform
import re
from datetime import date, datetime, time, timedelta, timezone, tzinfo
from decimal import Decimal
from typing import Dict

import pytest
import pytz
Expand Down Expand Up @@ -476,3 +478,38 @@ def test_tz_constraint_too_high():
def test_tz_constraint_wrong():
with pytest.raises(SchemaError, match="Input should be 'aware' or 'naive"):
SchemaValidator(core_schema.datetime_schema(tz_constraint='wrong'))


def test_tz_pickle() -> None:
"""
https://github.com/pydantic/pydantic-core/issues/589
"""
v = SchemaValidator(core_schema.datetime_schema())
original = datetime(2022, 6, 8, 12, 13, 14, tzinfo=timezone(timedelta(hours=-12, minutes=-15)))
validated = v.validate_python('2022-06-08T12:13:14-12:15')
assert validated == original
assert pickle.loads(pickle.dumps(validated)) == validated == original


def test_tz_hash() -> None:
v = SchemaValidator(core_schema.datetime_schema())
lookup: Dict[datetime, str] = {}
for day in range(1, 10):
input_str = f'2022-06-{day:02}T12:13:14-12:15'
validated = v.validate_python(input_str)
lookup[validated] = input_str

assert len(lookup) == 9
assert (
lookup[datetime(2022, 6, 8, 12, 13, 14, tzinfo=timezone(timedelta(hours=-12, minutes=-15)))]
== '2022-06-08T12:13:14-12:15'
)


def test_tz_cmp() -> None:
v = SchemaValidator(core_schema.datetime_schema())
validated1 = v.validate_python('2022-06-08T12:13:14-12:15')
validated2 = v.validate_python('2022-06-08T12:13:14-12:14')

assert validated1 > validated2
assert validated2 < validated1
Comment on lines +494 to +515
Copy link
Member Author

Choose a reason for hiding this comment

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

These are just testing existing properties