-
Notifications
You must be signed in to change notification settings - Fork 121
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat! [Python] リテラル型をnon exhaustiveに (#957)
#941, #955, #950 の続き。 `_Reserved`は`voicevox_core._models._please_do_not_use._Reserved`として でしか存在せず、ユーザーは原則触ることはできない状態にしてある。 BREAKING-CHANGE: Rust API, Java APIと同様`AccelerationMode`, `StyleType`, `UserDictWordType`がnon exhaustiveに。
- Loading branch information
Showing
3 changed files
with
152 additions
and
12 deletions.
There are no files selected for viewing
10 changes: 10 additions & 0 deletions
10
crates/voicevox_core_python_api/python/test/test_non_exhaustive_literal_types.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import pydantic | ||
import pytest | ||
from pydantic import TypeAdapter | ||
from voicevox_core import AccelerationMode, StyleType, UserDictWordType | ||
|
||
|
||
def test_invalid_input() -> None: | ||
for ty in [AccelerationMode, StyleType, UserDictWordType]: | ||
with pytest.raises(pydantic.ValidationError, match="^2 validation errors for"): | ||
TypeAdapter(ty).validate_python("不正な文字列") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
crates/voicevox_core_python_api/python/voicevox_core/_models/_please_do_not_use.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
from typing import Any, NoReturn | ||
|
||
from pydantic import GetCoreSchemaHandler | ||
from pydantic_core import CoreSchema, core_schema | ||
|
||
__all__ = ["_Reserved"] | ||
|
||
|
||
class _Reserved(str): | ||
def __new__(cls) -> NoReturn: | ||
raise TypeError() | ||
|
||
@classmethod | ||
def __get_pydantic_core_schema__( | ||
cls, source_type: Any, handler: GetCoreSchemaHandler | ||
) -> CoreSchema: | ||
_ = source_type, handler | ||
# TODO: pydantic/pydantic-core#1579 がリリースに入ったら`NeverSchema`にする | ||
return core_schema.no_info_after_validator_function( | ||
cls._no_input_allowed, core_schema.any_schema() | ||
) | ||
|
||
@classmethod | ||
def _no_input_allowed(cls, _: object) -> NoReturn: | ||
raise ValueError(f"No input is allowed for `{cls.__name__}`") |