API Reference¶
- zangar.Schema¶
alias of
SchemaBase
- zangar.ensure(func: Callable[[T], bool], /, **kwargs)¶
Ensure that the value satisfies the condition.
- Parameters:
func – The function to validate the value.
message – The error message to display when the validation fails.
- zangar.transform(func: Callable[[Any], T], /, **kwargs) Schema[T]¶
Transform the value.
- Parameters:
func – The function to transform the value.
message – The error message to display when the transformation fails.
- zangar.ref(name: str, /)¶
Create a reference to a schema.
- Parameters:
name – The name of the schema.
- Returns:
A schema that can parse the value using the referenced schema.
- zangar.isinstance(cls: type[T], /, **kwargs) Schema[T]¶
Validate that the value is an instance of the given class.
- This is equivalent to
z.ensure(lambda obj: isinstance(obj, cls)), but this function provides more effective type hints.
- Parameters:
cls – The class to check.
message – The error message to display when the validation fails.
- This is equivalent to
Base Types¶
- zangar.bool¶
alias of
ZangarBool
- zangar.datetime¶
alias of
ZangarDatetime
- zangar.float¶
alias of
ZangarFloat
- zangar.list¶
alias of
ZangarList
- zangar.none¶
alias of
ZangarNone
Conversions¶
- zangar.to.datetime¶
alias of
ZangarToDatetime
- zangar.to.float¶
alias of
ZangarToFloat
- zangar.to.int¶
alias of
ZangarToInt
- zangar.to.str¶
alias of
ZangarToStr
Structures¶
- zangar.struct¶
alias of
ZangarStruct
- zangar.mstruct¶
alias of
ZangarMappingStruct
- zangar.dataclass¶
alias of
ZangarDataclass
- zangar.field¶
alias of
ZangarField
- zangar.required_fields(fields: Mapping[str, ZangarField | SchemaBase], names: Iterable[str] | None = None, /) Mapping[str, ZangarField]¶
Make the specified fields required.
- Parameters:
fields – The fields to make required.
names – The names of the fields to make required. If not provided, all fields will be made required.
- zangar.optional_fields(fields: Mapping[str, ZangarField | SchemaBase], names: Iterable[str] | None = None, /) Mapping[str, ZangarField]¶
Make the specified fields optional.
- Parameters:
fields – The fields to make optional.
names – The names of the fields to make optional. If not provided, all fields will be made optional.
- zangar.pick_fields(fields: Mapping[str, ZangarField | SchemaBase], names: Iterable[str], /) Mapping[str, ZangarField]¶
Pick the specified fields.
- Parameters:
fields – The fields to pick from.
names – The names of the fields to pick.
- zangar.omit_fields(fields: Mapping[str, ZangarField | SchemaBase], names: Iterable[str], /) Mapping[str, ZangarField]¶
Pick all fields except the specified ones.
- Parameters:
fields – The fields to omit from.
names – The names of the fields to omit.
Private¶
- class zangar._core.SchemaBase¶
- class zangar._types.DatetimeMethods(*, prev: Schema[Any] | None = None, validator: TransformationValidator | EnsuranceValidator | None = None, meta: dict | None = None)¶
Bases:
Schema[datetime]- is_aware(**kwargs)¶
Validate the datetime is aware.
- is_naive(**kwargs)¶
Validate the datetime is naive.
- class zangar._types.NumberMethods(*, prev: Schema[Any] | None = None, validator: TransformationValidator | EnsuranceValidator | None = None, meta: dict | None = None)¶
Bases:
Schema- gt(value: int | float, /, **kwargs)¶
Validate the number is greater than a given value.
- Parameters:
value – The minimum value of the number.
message – The error message to display when the validation fails.
>>> z.int().gt(0).parse(1) 1 # equivalent to: >>> z.int().ensure(lambda x: x > 0).parse(1) 1
- gte(value: int | float, /, **kwargs)¶
Validate the number is greater than or equal to a given value.
- Parameters:
value – The minimum value of the number.
message – The error message to display when the validation fails.
>>> z.int().gte(0).parse(1) 1 # equivalent to: >>> z.int().ensure(lambda x: x >= 0).parse(1) 1
- lt(value: int | float, /, **kwargs)¶
Validate the number is less than a given value.
- Parameters:
value – The maximum value of the number.
message – The error message to display when the validation fails.
>>> z.int().lt(10).parse(1) 1 # equivalent to: >>> z.int().ensure(lambda x: x < 10).parse(1) 1
- lte(value: int | float, /, **kwargs)¶
Validate the number is less than or equal to a given value.
- Parameters:
value – The maximum value of the number.
message – The error message to display when the validation fails.
>>> z.int().lte(10).parse(1) 1 # equivalent to: >>> z.int().ensure(lambda x: x <= 10).parse(1) 1
- class zangar._types.StringMethods(*, prev: Schema[Any] | None = None, validator: TransformationValidator | EnsuranceValidator | None = None, meta: dict | None = None)¶
Bases:
Schema- max(value: int, /, **kwargs)¶
Validate the maximum length of a string.
- Parameters:
value – The maximum length of the string.
message – The error message to display when the validation fails.
>>> z.str().max(10).parse('hello') 'hello' # equivalent to: >>> z.str().ensure(lambda x: len(x) <= 10).parse('hello') 'hello'
- min(value: int, /, **kwargs)¶
Validate the minimum length of a string.
- Parameters:
value – The minimum length of the string.
message – The error message to display when the validation fails.
>>> z.str().min(1).parse('hello') 'hello' # equivalent to: >>> z.str().ensure(lambda x: len(x) >= 1).parse('hello') 'hello'
- strip(*args, **kwargs)¶
Trim whitespace from both ends.
>>> z.str().strip().parse(' hello ') 'hello' # equivalent to: >>> z.str().transform(lambda x: x.strip()).parse(' hello ') 'hello'
- class zangar._types.StructMethods(*args, name_to_alias: dict[str, str], **kwargs)¶
Bases:
Schema[T]- ensure_fields(fieldnames: list[str], func: Callable[[T], bool], /, *, message: Any | Callable[[T], Any] = None)¶
Validate the fields.
- Parameters:
fieldnames – The names of the fields to validate.
func – The function to validate the fields.
message – The error message to display when the validation fails.
- class zangar._types.ZangarAny(*, message=None, **kwargs)¶
Bases:
TypeSchemaValidate that the data is of any type.
- class zangar._types.ZangarBool(*, message=None, **kwargs)¶
Bases:
TypeSchema[bool]Validate that the data is of type
bool.>>> z.bool().parse(True) True # equivalent to: >>> z.ensure(lambda x: isinstance(x, bool)).parse(True) True
- class zangar._types.ZangarDataclass(cls: type[dataclasses._DataclassT], /)¶
Bases:
Schema[dataclasses._DataclassT]Convert a
dataclasses.dataclassinto a Zangar schema for data validation, and the resulting output is an instance of that dataclass.- Parameters:
cls – The dataclass to convert.
- property fields¶
The fields of the dataclass.
- class zangar._types.ZangarDatetime(*, message=None, **kwargs)¶
Bases:
TypeSchema[datetime],DatetimeMethodsValidate that the data is of type
datetime.datetime.equivalent to:
>>> z.datetime().parse(datetime.datetime(2000, 1, 1)) datetime.datetime(2000, 1, 1, 0, 0) # equivalent to: >>> ( ... z.ensure(lambda x: isinstance(x, datetime.datetime)) ... .parse(datetime.datetime(2000, 1, 1)) ... ) datetime.datetime(2000, 1, 1, 0, 0)
- class zangar._types.ZangarField(schema: SchemaBase[T], *, alias: str | None = None, getter: Callable[[Any], Any] | None = None, meta: Mapping | None = None)¶
Bases:
Generic[T]A field in a struct.
- Parameters:
- class zangar._types.ZangarFloat(*, message=None, **kwargs)¶
Bases:
TypeSchema[float],NumberMethodsValidate that the data is of type
float.>>> z.float().parse(1.0) 1.0 # equivalent to: >>> z.ensure(lambda x: isinstance(x, float)).parse(1.0) 1.0
- class zangar._types.ZangarInt(*, message=None, **kwargs)¶
Bases:
TypeSchema[int],NumberMethodsValidate that the data is of type
int.>>> z.int().parse(1) 1 # equivalent to: >>> z.ensure(lambda x: isinstance(x, int)).parse(1) 1
- class zangar._types.ZangarList(item: SchemaBase[T] | None = None, /, **kwargs)¶
Bases:
TypeSchema[List[T]]Validate that the data is of type
list.- Parameters:
item – The schema to validate the items in the list.
>>> z.list(z.transform(int)).parse(['1', 2]) [1, 2] # equivalent to: >>> ( ... z.ensure(lambda x: isinstance(x, list)) ... .transform(lambda x: [z.transform(int).parse(i) for i in x]) ... .parse(['1', 2]) ... ) [1, 2]
- class zangar._types.ZangarMappingStruct(*args, unknown: Literal['include', 'exclude', 'raise'] = 'exclude', **kwargs)¶
Bases:
ZangarStructOnly supports parsing
Mappingobjects.- Parameters:
unknown (str) –
The behavior when encountering unknown fields.
”include”: Include unknown fields in the parsed result.
”exclude”: Exclude unknown fields from the parsed result.
”raise”: Raise an error when encountering unknown fields.
- class zangar._types.ZangarNone(*, message=None, **kwargs)¶
Bases:
TypeSchema[None]Validate that the data is
None.>>> z.none().parse(None) # equivalent to: >>> z.ensure(lambda x: x is None).parse(None)
- class zangar._types.ZangarObject(*args, **kwargs)¶
Bases:
ZangarStructDeprecated, use
ZangarStructinstead.
- class zangar._types.ZangarStr(*, message=None, **kwargs)¶
Bases:
TypeSchema[str],StringMethodsValidate that the data is of type
str.>>> z.str().parse('hello') 'hello' # equivalent to: >>> z.ensure(lambda x: isinstance(x, str)).parse('hello') 'hello'
- class zangar._types.ZangarStruct(fields: Mapping[str, ZangarField | SchemaBase], /)¶
Bases:
TypeSchema[dict],StructMethods[dict]This is a schema with fields. It can parse any object and return a dict.
- Parameters:
fields – The fields of the struct.
- extend(fields: dict[str, ZangarField | SchemaBase], /)¶
Extend the struct with additional fields.
DEPRECATED: this method will be removed in the future.
- Parameters:
fields – The fields to add.
- property fields: FieldMapping¶
The fields of the struct.
- omit_fields(fieldnames: Iterable[str], /) ZangarStruct¶
Pick all fields except the specified ones.
DEPRECATED: this method will be removed in the future.
- Parameters:
fieldnames – The names of the fields to omit.
- optional_fields(fieldnames: Iterable[str] | None = None, /) ZangarStruct¶
Make the specified fields optional.
DEPRECATED: this method will be removed in the future.
- Parameters:
fieldnames – The names of the fields to make optional. If not provided, all fields will be made optional.
- pick_fields(fieldnames: Iterable[str], /) ZangarStruct¶
Pick the specified fields.
DEPRECATED: this method will be removed in the future.
- Parameters:
fieldnames – The names of the fields to pick.
- required_fields(fieldnames: Iterable[str] | None = None, /) ZangarStruct¶
Make the specified fields required.
DEPRECATED: this method will be removed in the future.
- Parameters:
fieldnames – The names of the fields to make required. If not provided, all fields will be made required.
- class zangar._types.ZangarToDatetime(*, message=None, **kwargs)¶
Bases:
ZangarDatetimeConvert the data to
datetime.datetime. It can parse a ISO 8601 datetime string.This feature is implemented using python-dateutil .
>>> z.to.datetime().parse('20040503T173008+08') datetime.datetime(2004, 5, 3, 17, 30, 8, tzinfo=tzoffset(None, 28800))
- class zangar._types.ZangarToFloat(*, message=None, **kwargs)¶
Bases:
ZangarFloatConvert the data to
float.>>> z.to.float().parse('1') 1.0 # equivalent to: >>> z.transform(float).parse('1') 1.0
- class zangar._types.ZangarToInt(*, message=None, **kwargs)¶
Bases:
ZangarIntConvert the data to
int.>>> z.to.int().parse('1.0') 1 # equivalent to: >>> z.transform(lambda x: int(float(x))).parse('1.0') 1>>> z.to.int().parse(1.1) Traceback (most recent call last): ... zangar.exceptions.ValidationError: [{'msgs': ['1.1 is not a valid integer']}]
- class zangar._types.ZangarToList(item: SchemaBase[T] | None = None, /, **kwargs)¶
Bases:
ZangarListConvert the data to
list.>>> z.to.list().parse((1, 2, 3)) [1, 2, 3] # equivalent to: >>> z.transform(list).parse((1, 2, 3)) [1, 2, 3]
Messages¶
- class zangar.MessageContext¶
The message context object can be used to modify Zangar’s default messages, and can also be extended to handle custom message types.
- process_message(message)¶
Process the message.
- Parameters:
message – The message to process.
- Returns:
The processed message.
- class zangar.DefaultMessage(key: str, value: ~typing.Any, ctx: dict = <factory>)¶
This is the wrapper class for Zangar’s default messages. You should not use it directly in your code, it exists solely for modifying Zangar’s built-in messages.