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

Fix encoding #22

Merged
merged 3 commits into from
Nov 21, 2024
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
4 changes: 4 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- Force utf-8 encoding when writing a config file (ini or yaml)

## v0.7.0 (2024-10-22)

### Changed
Expand Down
2 changes: 1 addition & 1 deletion confit/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def to_disk(self, path: Union[str, Path]):
s = self.to_yaml_str()
else:
s = Config.to_str(self)
Path(path).write_text(s)
Path(path).write_text(s, encoding="utf-8")

def serialize(self: Any):
"""
Expand Down
7 changes: 4 additions & 3 deletions confit/registry.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import inspect
import warnings
from functools import wraps
from typing import Any, Callable, Dict, Optional, Sequence, TypeVar
from typing import Any, Callable, Dict, Optional, Sequence, TypeVar, Union

import catalogue
import pydantic
Expand Down Expand Up @@ -32,6 +32,7 @@
import importlib_metadata

PYDANTIC_V1 = pydantic.VERSION.split(".")[0] == "1"
Func = TypeVar("Func")


def _resolve_and_validate_call(
Expand Down Expand Up @@ -147,12 +148,12 @@ def _check_signature_for_save_params(func: Callable):


def validate_arguments(
func: Optional[Callable] = None,
func: Optional[Func] = None,
*,
config: Dict = None,
invoker: Optional[Callable[[Callable, Dict[str, Any]], Any]] = None,
registry: Any = None,
) -> Any:
) -> Union[Func, Callable[[Func], Func]]:
"""
Decorator to validate the arguments passed to a function and store the result
in a mapping from results to call parameters (allowing
Expand Down
77 changes: 54 additions & 23 deletions tests/test_as_list.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,31 @@
from dataclasses import is_dataclass
from typing import Generic, List, TypeVar
from functools import lru_cache
from typing import TYPE_CHECKING, Generic, List, TypeVar, Union

import pydantic
import pytest
from pydantic import BaseModel
from typing_extensions import is_typeddict

from confit import validate_arguments
from confit.errors import ConfitValidationError, patch_errors

T = TypeVar("T")
if pydantic.VERSION < "2":

def cast(type_, obj):
class Model(pydantic.BaseModel):
__root__: type_

class Config:
arbitrary_types_allowed = True

return Model(__root__=obj).__root__

else:
from pydantic.type_adapter import ConfigDict, TypeAdapter
if pydantic.VERSION >= "2":
from pydantic_core import core_schema

def make_type_adapter(type_):
config = None
if not issubclass(type, BaseModel) or is_dataclass(type) or is_typeddict(type):
config = ConfigDict(arbitrary_types_allowed=True)
return TypeAdapter(type_, config=config)

def cast(type_, obj):
return make_type_adapter(type_).validate_python(obj)
class Validated:
@classmethod
def __get_validators__(cls):
yield cls.validate

@classmethod
def __get_pydantic_core_schema__(cls, source, handler):
return core_schema.chain_schema(
[
core_schema.no_info_plain_validator_function(v)
for v in cls.__get_validators__()
]
)


class MetaAsList(type):
Expand Down Expand Up @@ -68,6 +61,44 @@ class AsList(Generic[T], metaclass=MetaAsList):
pass


if pydantic.VERSION < "2":

def cast(type_, obj):
class Model(pydantic.BaseModel):
__root__: type_

class Config:
arbitrary_types_allowed = True

return Model(__root__=obj).__root__

else:
from dataclasses import is_dataclass

from pydantic import BaseModel
from pydantic.type_adapter import ConfigDict, TypeAdapter
from typing_extensions import is_typeddict

@lru_cache(maxsize=32)
def make_type_adapter(type_):
config = None

if not (
(isinstance(type_, type) and issubclass(type_, BaseModel))
or is_dataclass(type_)
or is_typeddict(type_)
):
config = ConfigDict(arbitrary_types_allowed=True)
return TypeAdapter(type_, config=config)

def cast(type_, obj):
return make_type_adapter(type_).validate_python(obj)


if TYPE_CHECKING:
AsList = Union[T, List[T]] # noqa: F811


def test_as_list():
@validate_arguments
def func(a: AsList[int]):
Expand Down
Loading