pygx.typing¶
Runtime typing for symbolic objects: schemas, fields, and value specs.
typing
¶
Runtime typing for symbolic objects: schemas, fields, and value specs.
Overview
To enable symbolic programmability on classes and functions, PyGX intercepts the assignment operation on the attributes of symbolic objects, to achieve two goals:
-
Enable automatic type checking, value validation, conversion and transformation on attribute values. See the Runtime typing section below for more details.
-
Allow symbolic attributes to be placeheld by markers, in order to represent abstract concepts such as a space of objects. E.g. hyper primitives like
pygx.oneofmark a symbolic attribute to create a space of values for that attribute. See the Markers section below for more details.
Runtime typing
Symbolic objects are intended to be manipulated after creation. Without a
runtime typing system, things can go wrong easily. For instance, an int
attribute which was mistakenly modified at early program stages can be very
difficult to debug at later stages. PyGX introduces a runtime type system
that automatically validates symbolic objects upon creation and modification,
minimizing boilerplated code for input validation, so the developer can focus
on the main business logic.
Understanding schema
PyGX's runtime type system is based on the concept of Schema (class
pygx.Schema), which defines what symbolic attributes
are held by a symbolic type (e.g. a symbolic dict, a symbolic list or a
symbolic class) and what values each attribute accepts. A Schema object
consists of a list of Field (class pygx.Field),
which define the acceptable keys (class
pygx.KeySpec) and their values (class
pygx.ValueSpec) for these types. A Schema
object is usually created automatically and associated with a symbolic type
upon its declaration, through dataclass-like field annotations on
pygx.Object or decorators such as
pygx.symbolize or
pygx.functor. For example:
class A(pg.Object):
x: int = 1
y: float | None = None
print(A.__schema__)
@pg.symbolize([
('a', pg.typing.Int()),
('b', pg.typing.Float())
])
def foo(a, b):
return a + b
print(foo.__schema__)
The first argument of pg.symbolize takes a list of field definitions, with
each described by a tuple of 4 items:
The key specification and value specification are required, while the doc string and the field metadata are optional. The key specification defines acceptable identifiers for this field, and the value specification defines the attribute's value type, its default value, validation rules. The doc string will serve as the description for the field, and the field metadata can be used for field-based code generation.
The following code snippet illustrates all supported KeySpec and
ValueSpec subclasses and their usage with a manually created schema:
class A(pg.Object):
x: int = 1
schema = pg.typing.create_schema([
# Primitive types.
('a', pg.typing.Bool(default=True).noneable()),
('b', True), # Equivalent to ('b', pg.typing.Bool(default=True)).
('c', pg.typing.Int()),
('d', 0), # Equivalent to ('d', pg.typing.Int(default=0)).
('e', pg.typing.Int(min_value=0, max_value=10).noneable()),
('f', pg.typing.Float()),
('g', 1.0), # Equivalent to ('g', pg.typing.Float(default=1.0)).
('h', pg.typing.Str()),
('i', 'foo'), # Equivalent to ('i', pg.typing.Str(default='foo')).
('j', pg.typing.Str(regex='foo.*')),
# Enum type.
('l', pg.typing.Enum(['foo', 'bar', 0, 1], 'foo')),
# List type.
('m', pg.typing.List(pg.typing.Int(), size=2, default=[0, 0])),
('n', pg.typing.List(pg.typing.Dict([
('n1', pg.typing.List(pg.typing.Int())),
('n2', pg.typing.Str().noneable()),
]), min_size=1, max_size=10)),
# Dict type.
('o', pg.typing.Dict([
('o1', pg.typing.Int()),
('o2', pg.typing.List(pg.typing.Dict([
('o21', 1),
('o22', 1.0),
]))),
('o3', pg.typing.Dict([
# Use of regex key.
(pg.typing.StrKey('n3.*'), pg.typing.Int()),
])),
])),
# Tuple type.
('p', pg.typing.Tuple([pg.typing.Int(), pg.typing.Str()])),
# Object type.
('q', pg.typing.Object(A, default=A())),
# Type type.
('r', pg.typing.Type(int)),
# Callable type.
('s', pg.typing.Callable([pg.typing.Int(), pg.typing.Int()],
kw=[('a', pg.typing.Str())])),
# Functor type (same as Callable, but only for symbolic.Functor).
('t', pg.typing.Functor([pg.typing.Str()],
kw=[('a', pg.typing.Str())])),
# Union type.
('u', pg.typing.Union([pg.typing.Int(), pg.typing.Str()], default=1)),
# Any type.
('v', pg.typing.Any(default=1)),
])
From Python annotations
For most classes there is no need to hand-build value specs: standard Python
type annotations on a pygx.Object subclass convert
to value specs automatically. The conversion rules:
int,str,bool,floatmap topygx.typing.Int,pygx.typing.Str,pygx.typing.Bool,pygx.typing.Float.X | None(ortyping.Optional[X]) makes the field acceptNone; other unions (A | B) map topygx.typing.Union.typing.Literal[...]maps topygx.typing.Enum.list[E]/dict[str, V]map topygx.typing.List/pygx.typing.Dictspecs holding plainlist/dictvalues, whilepg.List[E]/pg.Dict[str, V]annotations produce the same specs with symbolic storage: assigned raw containers are converted into symbolicpg.List/pg.Dictinstances. A trailingtyping.Literal[False]type argument (e.g.pg.List[E, typing.Literal[False]]) setsauto_wrap=False: the annotated container itself is still symbolic, but rawdict/listvalues landing in member positions the spec leaves unconstrained (e.g.Any-typed elements) are kept verbatim instead of being wrapped into their symbolic forms.- A
typing.TypedDictsubclass maps to apygx.typing.Dictspec mirroring its keys; extra keys are rejected unless the TypedDict declares PEP 728extra_items=.... - PEP 695 type aliases (
type IntList = list[int]), including subscripted generic aliases (Pair[int]), expand to their aliased values. - Stdlib scalars such as
datetime.datetime,uuid.UUID,decimal.Decimalandpathlib.Pathmap to dedicated specs (pygx.typing.Datetime,pygx.typing.Uuid, ...); any other class maps topygx.typing.Object.
ValueSpec instances themselves are not accepted as annotations (static
type checkers cannot read them). To attach an explicit value spec to a
field, pass it via pg.field(value_spec=...) — either as the field's
default or inside typing.Annotated:
import typing
class A(pg.Object):
x: typing.Annotated[int, pg.field(value_spec=pg.typing.Int(min_value=0))]
y: int = pg.field(default=1, value_spec=pg.typing.Int(max_value=10))
To validate a bare value against an annotation in one line, use
pygx.validate.
Schema inheritance
Symbolic attributes can be inherited during subclassing. Accordingly, the
schema that defines a symbolic class' attributes can be inherited too by its
subclasses. The fields from the bases' schema will be carried over into the
subclasses' schema, while the subclass can override, by redefining that
field with the same key. The subclass cannot override its base classes'
field with arbitrary value specs, it must be overriding non-frozen fields
with more restrictive validation rules of the same type, or change their
default values. See pygx.ValueSpec.extend
for more details.
The code snippet below illustrates schema inheritance during subclassing:
import typing
class A(pg.Object):
x: typing.Annotated[
int, pg.field(value_spec=pg.typing.Int(min_value=1))]
y: float
class B(A):
# Further restrict inherited 'x' by specifying the max value, as well
# as providing a default value.
x: typing.Annotated[
int, pg.field(value_spec=pg.typing.Int(max_value=5, default=2))]
z: str = pg.field(value_spec=pg.typing.Str(default='foo').freeze())
assert list(B.__schema__.fields.keys()) == ['x', 'y', 'z']
class C(B):
# Raises: 'z' is frozen in class B and cannot be extended further.
z: str
Automatic type conversions
When a value is assigned to an attribute whose value specification does not
match the input value type, a coercion takes place automatically if the
target type knows how to accept the input. A type opts in by defining a
__pg_accept__(value) classmethod that returns a converted instance (or
NotImplemented to decline). For example:
class A:
def __init__(self, s):
self._str = s
def __eq__(self, other):
return isinstance(other, self.__class__) and self._str == other._str
@classmethod
def __pg_accept__(cls, value):
return cls(value) if isinstance(value, str) else NotImplemented
assert pg.typing.Object(A).apply('abc') == A('abc')
For builtin targets that cannot host a classmethod, use a field-level
pg.field(transform=...) instead. The universal int → float
widening is intrinsic to pg.typing.Float.
Markers
Markers (formerly "symbolic placeholding") enable scenarios that require an abstract (non-material) representation of objects - for example - a search space or a partially bound object. Such objects with marked attributes can only be used symbolically, which means they can be symbolically queried or manipulated, but not yet materialized to execute the business logic. For example:
@pg.functor()
def foo(x, y):
return x + y
f = foo(x=pg.oneof(range(5)), y=pg.floatv(0.0, 2.0))
# Error: `x` and `y` are not materialized, thus the functor cannot be
# executed.
# f()
# But we can symbolically manipulate it:
f.sym_rebind(x=1, y=2)
# Returns 3
assert f() == 3
Markers are built on the pygx.CustomTyping
interface, a mechanism to extend the typing system horizontally without
modifying the pygx.ValueSpec of existing classes'
attributes: CustomTyping subclasses take over value validation and
transformation from an attribute's original ValueSpec via the
pygx.CustomTyping.custom_apply
method.
Following is an example of using CustomTyping to extend the schema
system — a Ratio object that can sit in any float-typed attribute:
class Ratio(pg.typing.CustomTyping):
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def custom_apply(
self, path, value_spec, allow_partial, child_transform=None):
if isinstance(value_spec, pg.typing.Float):
# Validate the ratio's value against the spec's constraints
# (e.g. min_value/max_value).
value_spec.apply(self.numerator / self.denominator)
# Short-circuit `.apply` and return the object itself as the
# final value.
return (False, self)
else:
raise ValueError(
f'Ratio can only be applied to float type. (path={path})')
class Foo(pg.Object):
x: float
# Ratio is accepted for all symbolic attributes with a Float value spec.
f = Foo(x=Ratio(1, 2))
assert isinstance(f.x, Ratio)
MissingValue
¶
Bases: Formattable, WireConvertible
Value placeholder for an unassigned attribute.
pg.MISSING_VALUE is the canonical instance: field machinery uses it
to mark a declared field whose value has not been provided (see
MaybePartial). All MissingValue instances compare equal (and share
one hash), it is wire-convertible, and the class cannot be subclassed --
the symbolic core detects the sentinel with an exact-type check on its
hot paths.
Argument
dataclass
¶
Definition for a callable argument.
Kind
¶
Bases: Enum
Argument kind.
from_parameter
classmethod
¶
from_parameter(parameter: Parameter) -> Kind
Returns Argument.Kind from inspect.Parameter.
Source code in pygx/typing/_callable_signature.py
from_annotation
classmethod
¶
from_annotation(
name: str,
kind: Kind,
annotation: Any = empty,
auto_typing: bool = False,
parent_module: ModuleType | None = None,
) -> Argument
Creates an argument from annotation.
Source code in pygx/typing/_callable_signature.py
from_parameter
classmethod
¶
from_parameter(
param: Parameter,
description: str | None = None,
auto_typing: bool = True,
parent_module: ModuleType | None = None,
) -> Argument
Creates an argument from inspect.Parameter.
Source code in pygx/typing/_callable_signature.py
to_field
¶
to_field() -> Field
Converts current argument to a pg.typing.Field object.
Source code in pygx/typing/_callable_signature.py
CallableType
¶
Bases: Enum
Enum for Callable type.
Signature
¶
Signature(
callable_type: CallableType,
name: str,
module_name: str | None,
args: list[Argument] | None = None,
kwonlyargs: list[Argument] | None = None,
varargs: Argument | None = None,
varkw: Argument | None = None,
return_value: ValueSpec | None = None,
qualname: str | None = None,
description: str | None = None,
)
Bases: Formattable
A callable's signature, with a value spec attached to each argument.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callable_type
|
CallableType
|
Type of callable. |
required |
name
|
str
|
Function name. |
required |
module_name
|
str | None
|
Module name. |
required |
args
|
list[Argument] | None
|
Specification for positional arguments. |
None
|
kwonlyargs
|
list[Argument] | None
|
Specification for keyword-only arguments. |
None
|
varargs
|
Argument | None
|
Specification for wildcard list argument, e.g. 'args' is the
name for |
None
|
varkw
|
Argument | None
|
Specification for wildcard keyword argument, e.g. 'kwargs' is
the name for |
None
|
return_value
|
ValueSpec | None
|
Optional value spec for return value. |
None
|
qualname
|
str | None
|
Optional qualified name. |
None
|
description
|
str | None
|
Optional description of the signature. |
None
|
Source code in pygx/typing/_callable_signature.py
named_args
property
¶
named_args: list[Argument]
Returns all named arguments according to their declaration order.
has_wildcard_args
property
¶
Returns whether any wildcard arguments are present.
get_value_spec
¶
get_value_spec(name: str) -> ValueSpec | None
Returns Value spec for an argument name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Argument name. |
required |
Returns:
| Type | Description |
|---|---|
ValueSpec | None
|
ValueSpec for the requested argument. If name is not found, value spec of |
ValueSpec | None
|
wildcard keyword argument will be used. None will be returned if name |
ValueSpec | None
|
does not exist in signature and wildcard keyword is not accepted. |
Source code in pygx/typing/_callable_signature.py
format
¶
Format current object.
Source code in pygx/typing/_callable_signature.py
annotate
¶
annotate(
args: (
dict[FieldKeyDef, FieldValueDef] | list[FieldDef | Field] | None
) = None,
return_value: ValueSpec | Any | None = None,
) -> Signature
Annotate arguments with extra typing.
Source code in pygx/typing/_callable_signature.py
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | |
fields
¶
fields(remove_self: bool = True, include_return: bool = False) -> list[Field]
Returns the fields of this signature.
Source code in pygx/typing/_callable_signature.py
to_schema
¶
to_schema(remove_self: bool = True, include_return: bool = False) -> Schema
Returns the schema of this signature.
Source code in pygx/typing/_callable_signature.py
from_schema
classmethod
¶
from_schema(
schema: Schema,
module_name: str,
name: str,
qualname: str | None = None,
is_method: bool = True,
use_init_arg_list: bool = False,
) -> Signature
Creates a signature from a schema object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
Schema
|
A |
required |
module_name
|
str
|
Module name for the signature. |
required |
name
|
str
|
Function or method name of the signature. |
required |
qualname
|
str | None
|
Qualname of the signature. |
None
|
is_method
|
bool
|
If True, |
True
|
use_init_arg_list
|
bool
|
If True, honor the schema's |
False
|
Returns:
| Type | Description |
|---|---|
Signature
|
A signature object from the schema. |
Source code in pygx/typing/_callable_signature.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 | |
from_callable
classmethod
¶
from_callable(
callable_object: Callable[..., Any],
auto_typing: bool = False,
auto_doc: bool = False,
) -> Signature
Creates Signature from a callable object.
Source code in pygx/typing/_callable_signature.py
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 | |
from_signature
classmethod
¶
from_signature(
sig: Signature,
name: str,
callable_type: CallableType,
module_name: str | None = None,
qualname: str | None = None,
auto_typing: bool = False,
docstr: str | DocStr | None = None,
parent_module: ModuleType | None = None,
) -> Signature
Returns PyGX signature from Python signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sig
|
Signature
|
Python signature. |
required |
name
|
str
|
Name of the entity (class name or function/method name). |
required |
callable_type
|
CallableType
|
the type of this callable. |
required |
module_name
|
str | None
|
Module name of the entity. |
None
|
qualname
|
str | None
|
(Optional) qualified name of the entity. |
None
|
auto_typing
|
bool
|
If True, automatically convert argument annotations to PyGX ValueSpec objects. Otherwise use pg.typing.Any() with annotations. |
False
|
docstr
|
str | DocStr | None
|
(Optional) DocStr for this entity. |
None
|
parent_module
|
ModuleType | None
|
(Optional) Parent module from where the signature is derived. This is useful to infer classes with forward declarations. |
None
|
Returns:
| Type | Description |
|---|---|
Signature
|
A PyGX Signature object. |
Source code in pygx/typing/_callable_signature.py
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 | |
make_function
¶
make_function(
body: list[str],
exec_globals: dict[str, Any] | None = None,
exec_locals: dict[str, Any] | None = None,
)
Makes a function with current signature.
Source code in pygx/typing/_callable_signature.py
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 | |
Field
¶
Field(
key_spec: KeySpec | str,
value_spec: ValueSpec,
description: str | None = None,
metadata: dict[str, Any] | None = None,
origin: type[Any] | None = None,
*,
enable_repr: bool | None = None,
enable_compare: bool | None = None,
enable_hash: bool | None = None,
enable_init: bool = True,
enable_clone: bool | None = None,
enable_validation: bool | None = None,
assign: str | None = None,
alias: str | None = None
)
Bases: Formattable, WireConvertible
Class that represents the definition of one or a group of attributes.
Field is held by a pygx.Schema object for defining the
name(s), the validation and transformation rules on its/their value(s) for a
single symbolic attribute or a set of symbolic attributes.
A Field is defined by a tuple of 4 items:
For example:
The key specification (or KeySpec, class pygx.KeySpec) and
value specification (or ValueSpec, class pygx.ValueSpec) are
required, while the doc string and the field metadata are optional. The
KeySpec defines acceptable identifiers for this field, and the
ValueSpec defines the attribute's value type, its default value,
validation rules and etc. The doc string serves as the description for the
field, and the field metadata can be used for attribute-based code generation.
Field supports extension, which allows the subclass to add more
restrictions to a field inherited from the base class, or override its default
value. A field can be frozen so that subclasses can no longer extend it.
See pygx.KeySpec and pygx.ValueSpec for details.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_spec
|
KeySpec | str
|
Key specification of the field. Can be a string or a KeySpec instance. |
required |
value_spec
|
ValueSpec
|
Value specification of the field. |
required |
description
|
str | None
|
Description of the field. |
None
|
metadata
|
dict[str, Any] | None
|
A dict of objects as metadata for the field. |
None
|
origin
|
type[Any] | None
|
The class that this field originates from. |
None
|
enable_repr
|
bool | None
|
Whether this field appears in |
None
|
enable_compare
|
bool | None
|
Whether this field participates in symbolic
equality. Same |
None
|
enable_hash
|
bool | None
|
Whether this field participates in symbolic
hashing. Same |
None
|
enable_init
|
bool
|
If False, the field is excluded from the generated
|
True
|
enable_clone
|
bool | None
|
Only meaningful when |
None
|
enable_validation
|
bool | None
|
Whether values are validated against the
field's value spec. Same |
None
|
assign
|
str | None
|
How this field takes the value it is given.
|
None
|
alias
|
str | None
|
Optional wire-layer alias for this field's key (#517):
accepted by |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
metadata is not a dict. |
Source code in pygx/typing/_class_schema.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 | |
metadata
property
¶
Metadata of this field.
Metadata is defined as a dict type, so multiple annotations can be attached to a field and retrieved by key:
field = pg.typing.Field('x', pg.typing.Int(), 'An int field.',
{'userdata': 1})
assert field.metadata.get('userdata', None) == 1
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Metadata of this field as a dict. |
enable_repr
property
¶
Whether to include this field in pg.Object.format / repr.
None resolves to enable_init (symbolic → True,
non-symbolic → False).
enable_compare
property
¶
Whether to include this field in symbolic equality comparisons.
None resolves to enable_init (symbolic → True,
non-symbolic → False).
enable_hash
property
¶
Whether to include this field in symbolic hashing.
None resolves to enable_init (symbolic → True,
non-symbolic → False).
enable_clone
property
¶
Whether a non-symbolic field is copied during sym_clone.
Only consulted when enable_init is False (a no-op otherwise:
symbolic fields always participate in sym_clone). None
resolves to enable_init — i.e. False for non-symbolic,
which means the clone re-seeds from the default / leaves the
field unset and on_sym_ready recomputes.
enable_validation
property
¶
Whether values flow through ValueSpec.apply for type checking.
None resolves to enable_init (symbolic → True,
non-symbolic → False).
assign
property
¶
How this field takes its value: 'adopt' / 'clone' / 'ref' / None.
'adopt' takes a free value as-is and copies a held one
(topo=True only); 'clone' always copies; 'ref' shares
one node. None means UNDECLARED — a second hold raises
SharedHoldError so the caller picks. It is deliberately not a
silent default: that is the ambiguity the error exists to remove.
validator
property
¶
User validator called on the final value apply produces.
alias
property
¶
Wire-layer alias for this field's key (#517).
Honored by from_json (the alias key is accepted for this
field), to_json(by_alias=True) (emitted in place of the field
name), and JSON Schema emission. Python attribute access and
__init__ kwargs always use the field name.
from_annotation
classmethod
¶
from_annotation(
key: str | KeySpec,
annotation: Any,
description: str | None = None,
metadata: dict[str, Any] | None = None,
auto_typing=True,
parent_module: ModuleType | None = None,
) -> Field
Gets a Field from annotation.
Source code in pygx/typing/_class_schema.py
set_description
¶
_own_value_spec
¶
Copy-on-write ownership of the value spec (#535 review B1/M3).
pg.field(value_spec=...) embeds the user's spec object verbatim, and
a spec may be shared with another class or already latched into
another class's fast-path metadata — never mutate a spec this field
does not own. Deep-clones the spec and swaps it in; fields themselves
are per-class copies, so the swap is safe. Any writer that
materializes CLASS-dependent state onto the spec (strictness, no-wrap
default formalization) must take ownership first.
Source code in pygx/typing/_class_schema.py
set_origin
¶
set_validator
¶
Sets the user validator callable and returns self.
The validator is the field-level after check: Field.apply
calls it with the final value — after the value spec accepted
(and possibly coerced/wrapped) it — and it rejects by raising.
Its return value is ignored: transformation is transform's
job (the before hook on the value spec), so validation and
coercion stay separate concerns. Exposed as a setter so
pg.field(validator=...) can attach it to annotation-style
fields.
Source code in pygx/typing/_class_schema.py
set_alias
¶
Sets the wire-layer alias and returns self.
Exposed as a setter so pg.field(alias=...) can attach it to
annotation-style fields. Cross-field checks (uniqueness, no
collision with sibling field names or the _type wire key)
run where all fields are known — at class creation.
Source code in pygx/typing/_class_schema.py
extend
¶
extend(base_field: Field) -> Self
Extend current field based on a base field.
Source code in pygx/typing/_class_schema.py
apply
¶
apply(
value: Any,
allow_partial: bool = False,
transform_fn: None | Callable[[KeyPath, Field, Any], Any] = None,
root_path: KeyPath | None = None,
inplace: bool = True,
) -> Any
Applies this field to a value, validating and completing it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate against this spec. |
required |
allow_partial
|
bool
|
Whether partial value is allowed. This is for dict or nested dict values. |
False
|
transform_fn
|
None | Callable[[KeyPath, Field, Any], Any]
|
Function to transform applied value into final value. |
None
|
root_path
|
KeyPath | None
|
Key path for root. |
None
|
inplace
|
bool
|
If False, containers are validated on a copy so the caller's input is left untouched. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
final value. |
Any
|
When allow_partial is set to False (default), only fully qualified value |
Any
|
is acceptable. When allow_partial is set to True, missing fields will |
Any
|
be placeheld using MISSING_VALUE. |
Raises:
| Type | Description |
|---|---|
KeyError
|
if additional key is found in value, or required key is missing and allow_partial is set to False. |
TypeError
|
if type of value is not the same as spec required. |
ValueError
|
if value is not acceptable, or value is MISSING_VALUE while
allow_partial is set to False, or the field's |
Source code in pygx/typing/_class_schema.py
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 | |
format
¶
Format this field into a string.
Source code in pygx/typing/_class_schema.py
ForwardRef
¶
Bases: Formattable
Forward type reference.
Source code in pygx/typing/_class_schema.py
bind
¶
Resolve this ForwardRef instance to cls.
Per-instance: equal-but-distinct refs are not affected. Used by
Schema to wire local classes into their own self-references
and to satisfy sibling cross-references once both endpoints exist.
Source code in pygx/typing/_class_schema.py
as_annotation
¶
format
¶
Format this object.
Source code in pygx/typing/_class_schema.py
KeySpec
¶
Bases: Formattable, WireConvertible
Interface for key specifications.
A key specification determines what keys are acceptable for a symbolic
field (see pygx.Field). Usually, symbolic attributes have a 1:1
relationship with symbolic fields. But in some cases (e.g. a dict with dynamic
keys), a field can be used to describe a group of symbolic attributes:
# A dictionary that accepts key 'x' with float value
# or keys started with 'foo' with int values.
d = pg.Dict({'x': 1.0, 'foo1': 1}, value_spec=pg.typing.Dict([
('x', pg.typing.Float(min_value=0.0)),
(pg.typing.StrKey('foo.*'), pg.typing.Int())
]))
You may have noticed that the code above passes a string 'x' as the key
spec for a field definition. The string is automatically converted to
pygx.typing.ConstStrKey.
PyGX's builtin key specifications are:
KeySpec type |
Class |
|---|---|
| Fixed string identifier | pygx.typing.ConstStrKey |
| Dynamic string identifier | pygx.typing.StrKey |
| Key of a list | pygx.typing.ListKey |
| Key of a tuple | pygx.typing.TupleKey |
In most scenarios, the user uses either a string or a StrKey as the key
spec, while other KeySpec subclasses (e.g. ListKey and TupleKey)
are used internally to constrain list size and tuple items.
const_text
property
¶
For const string keys, returns the literal key text; else None.
Default returns None. ConstStrKey overrides to return its text.
Schema's per-field precompute paths read this instead of casting to
a concrete key type — avoids any dependency on _key_specs.
match
abstractmethod
¶
extend
abstractmethod
¶
extend(base: KeySpec) -> Self
Extend base key specification and returns self.
NOTE(daiyip): When a Field extends a base Field (from a base schema),
it calls extend on both its KeySpec and ValueSpec.
KeySpec.extend is to determine whether the Field key is allowed to
be extended, and ValueSpec.extend is to determine the final
ValueSpec after extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
KeySpec
|
A base |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A |
Source code in pygx/typing/_class_schema.py
from_str
classmethod
¶
Schema
¶
Schema(
fields: list[Field],
name: str | None = None,
base_schema_list: list[Schema] | None = None,
description: str | None = None,
*,
allow_nonconst_keys: bool = False,
metadata: dict[str, Any] | None = None,
for_cls: type[Any] | None = None
)
Bases: Formattable, WireConvertible
Class that represents a schema.
PyGX's runtime type system is based on the concept of Schema (
class pygx.Schema), which defines what symbolic attributes are
held by a symbolic type (e.g. a symbolic dict, a symbolic list or a symbolic
class) and what values each attribute accepts. A Schema object consists of
a list of Field (class pygx.Field), which define the
acceptable keys and their values for these attributes. A Schema object is
usually created automatically and associated with a symbolic type upon its
declaration, through dataclass-like field annotations on pygx.Object
or decorators such as pygx.symbolize or pygx.functor. For
example:
class A(pg.Object):
x: int = 1
y: float | None = None
print(A.__schema__)
@pg.symbolize([
('a', pg.typing.Int()),
('b', pg.typing.Float())
])
def foo(a, b):
return a + b
print(foo.__schema__)
Implementation-wise it holds an ordered dictionary of a field key
(pygx.KeySpec) to its field definition (pygx.Field).
The key specification describes what keys/attributes are acceptable for the
field, and value specification within the Field describes the value type
of the field and their validation rules, default values, and etc.
Symbolic attributes can be inherited during subclassing. Accordingly, the
schema that defines a symbolic class' attributes can be inherited too by its
subclasses. The fields from the bases' schema will be carried over into the
subclasses' schema, while the subclass can override, by redefining that field
with the same key. The subclass cannot override its base classes' field with
arbitrary value specs, it must be overriding non-frozen fields with more
restrictive validation rules of the same type, or change their default values.
See pygx.ValueSpec.extend for more details.
The code snippet below illustrates schema inheritance during subclassing:
class A(pg.Object):
x: typing.Annotated[
int, pg.field(value_spec=pg.typing.Int(min_value=1))
]
y: float
class B(A):
# Further restrict inherited 'x' by specifying the max value, as well
# as providing a default value.
x: typing.Annotated[
int, pg.field(value_spec=pg.typing.Int(max_value=5, default=2))
]
z: typing.Annotated[
str, pg.field(value_spec=pg.typing.Str().freeze('foo'))
]
assert list(B.__schema__.fields.keys()) == ['x', 'y', 'z']
class C(B):
# Raises: 'z' is frozen in class B and cannot be extended further.
z: str
With a schema, an input dict can be validated and completed by the schema
via apply. A key that matches no field raises KeyError; a missing
required field raises unless allow_partial is set to True, in which
case a partially validated/transformed dict is returned, with missing
values placeheld by pg.MISSING_VALUE.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
list[Field]
|
A list of Field as the definition of the schema. The order of the fields will be preserved. |
required |
name
|
str | None
|
Optional name of this schema. Useful for debugging. |
None
|
base_schema_list
|
list[Schema] | None
|
List of schema used as base. When present, fields from these schema will be copied to this schema. Fields from the latter schema will override those from the former ones. |
None
|
description
|
str | None
|
Optional str as the description for the schema. |
None
|
allow_nonconst_keys
|
bool
|
Whether immediate fields can use non-const keys. |
False
|
metadata
|
dict[str, Any] | None
|
Optional dict of user objects as schema-level metadata. |
None
|
for_cls
|
type[Any] | None
|
Optional class that this schema applies to. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
Argument |
KeyError
|
If a field name contains characters ('.') which is not
allowed, or a field name from |
ValueError
|
When failed to create ValueSpec from |
Source code in pygx/typing/_class_schema.py
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 | |
dynamic_field
property
¶
dynamic_field: Field | None
Returns the field that matches multiple keys if any.
merge
classmethod
¶
merge(
schema_list: Sequence[Schema],
name: str | None = None,
description: str | None = None,
) -> Schema
Merge multiple schemas into one.
For fields shared by multiple schemas, the first appearance wins,
unless a later field's origin class is a subclass of the
earlier one's — then the more derived definition takes over.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema_list
|
Sequence[Schema]
|
A list of schemas to merge. |
required |
name
|
str | None
|
(Optional) name of the merged schema. |
None
|
description
|
str | None
|
(Optional) description of the schema. |
None
|
Returns:
| Type | Description |
|---|---|
Schema
|
The merged schema. |
Source code in pygx/typing/_class_schema.py
extend
¶
extend(base: Schema) -> Self
Extend current schema based on a base schema.
Source code in pygx/typing/_class_schema.py
is_compatible
¶
is_compatible(other: Schema) -> bool
Returns whether current schema is compatible with the other schema.
NOTE(daiyip): schema A is compatible with schema B when: schema A and schema B have the same keys, with compatible values specs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Schema
|
Other schema. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if values acceptable to the other schema are acceptable to the current schema. |
Raises:
TypeError: If other is not a schema object.
Source code in pygx/typing/_class_schema.py
get_field
¶
get_field(key: str | int) -> Field | None
Get field definition (Field) for a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str | int
|
Key to look up — a string key name, or an int (e.g. a list
index matched against a |
required |
Returns:
| Type | Description |
|---|---|
Field | None
|
Matched field. A field is considered a match when: * Its key spec is a ConstStrKey that equals to the input key. * Or it's the first field whose key spec is a NonConstKey which matches the input key. |
Source code in pygx/typing/_class_schema.py
set_description
¶
resolve
¶
resolve(
keys: Iterable[str | int],
) -> tuple[dict[KeySpec, list[str]], list[str | int]]
Resolve keys by grouping them by their matched fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Iterable[str | int]
|
A list of string keys. |
required |
Returns:
| Type | Description |
|---|---|
tuple[dict[KeySpec, list[str]], list[str | int]]
|
A tuple of matched key results and unmatched keys. Matched key results are an ordered dict of KeySpec to matched keys, in field declaration order. Unmatched keys are strings from input. |
Source code in pygx/typing/_class_schema.py
apply
¶
apply(
dict_obj: dict[str, Any],
allow_partial: bool = False,
child_transform: None | Callable[[KeyPath, Field, Any], Any] = None,
root_path: KeyPath | None = None,
respect_raw_storage: bool | None = None,
inplace: bool = True,
) -> dict[str, Any]
Apply this schema to a dict object, validate and transform it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dict_obj
|
dict[str, Any]
|
JSON dict type that (maybe) conform to the schema. |
required |
allow_partial
|
bool
|
Whether allow partial object to be created. |
False
|
child_transform
|
None | Callable[[KeyPath, Field, Any], Any]
|
Function to transform child node values in dict_obj into
their final values. Transform function is called on leaf nodes first,
then on their containers, recursively.
The signature of transform_fn is: Return value will be inserted to the parent dict under path, unless return value is MISSING_VALUE. |
None
|
root_path
|
KeyPath | None
|
KeyPath of root element of dict_obj. |
None
|
respect_raw_storage
|
bool | None
|
Per-field gating of |
None
|
inplace
|
bool
|
When True (default), validate/transform |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict filled by the schema with transformed values. |
Raises:
| Type | Description |
|---|---|
KeyError
|
Key is not allowed in schema. |
TypeError
|
Type of dict values are not aligned with schema. |
ValueError
|
Value of dict values are not aligned with schema. |
Source code in pygx/typing/_class_schema.py
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 | |
validate
¶
validate(
dict_obj: dict[str, Any],
allow_partial: bool = False,
root_path: KeyPath | None = None,
) -> None
Validates whether the dict object conforms to the schema.
Source code in pygx/typing/_class_schema.py
set_name
¶
get
¶
Returns field by key with default value if not found.
items
¶
format
¶
format(
compact: bool = False,
verbose: bool = True,
root_indent: int = 0,
*,
cls_name: str | None = None,
bracket_type: BracketType = ROUND,
fields_only: bool = False,
**kwargs
) -> str
Format current Schema into nicely printed string.
Source code in pygx/typing/_class_schema.py
to_json_schema
¶
to_json_schema(
*,
include_type_name: bool = True,
include_subclasses: bool = False,
inline_nested_refs: bool = False,
**kwargs
) -> dict[str, Any]
Converts this field to JSON schema.
Source code in pygx/typing/_class_schema.py
from_json_schema
classmethod
¶
from_json_schema(
json_schema: dict[str, Any],
class_fn: Callable[[str, Schema], type[Any]] | None = None,
add_json_schema_as_metadata: bool = False,
) -> Schema
Converts a JSON schema to a schema.
Source code in pygx/typing/_class_schema.py
ValueSpec
¶
Bases: Formattable, WireConvertible
Interface for value specifications.
A value specification defines what values are acceptable for a symbolic
field (see pygx.Field). When assignments take place on the
attributes for the field, the associated ValueSpec object will kick in to
intercept the process and take care of the following aspects:
- Type check
- Noneable check
- Value validation and transformation
- Default value assignment
See .apply for more details.
Different aspects of assignment interception are handled by the following methods:
| Aspect name | Property/Method |
|---|---|
| Type check | .value_type |
| Noneable check | .is_noneable |
| Type-specific value validation & transformation | .apply |
| User transform | .transform |
| Default value lookup | .default |
There are many ValueSpec subclasses, each correspond to a commonly used
Python type, e.g. Bool, Int, Float and etc. PyGX's builtin value
specifications are:
ValueSpec type |
Class |
|---|---|
| bool | pygx.typing.Bool |
| int | pygx.typing.Int |
| float | pygx.typing.Float |
| str | pygx.typing.Str |
| enum | pygx.typing.Enum |
| list | pygx.typing.List |
| tuple | pygx.typing.Tuple |
| dict | pygx.typing.Dict |
| instance of a class | pygx.typing.Object |
| callable | pygx.typing.Callable |
| functor | pygx.typing.Functor |
| type | pygx.typing.Type |
| union | pygx.typing.Union |
| any | pygx.typing.Any |
Construction
A value specification is an instance of a ValueSpec subclass. All
pygx.ValueSpec subclasses follow a common pattern to construct:
After creation, a ValueSpec object can be modified with chaining.
The code below creates an int specification with default value 1 and can
accept None:
Usage
To apply a value specification on an user input to get the accepted value,
pygx.ValueSpec.apply shall be used:
Extension
Besides, a ValueSpec object can extend another ValueSpec object to
obtain a more restricted ValueSpec object. For example:
will end up with:
which will be useful when subclass adds additional restrictions to an inherited symbolic attribute from its base class. For some use cases, a value spec can be frozen to avoid subclass extensions:
ValueSpec objects can be created and modified with chaining. For example:
The code above creates an int specification with default value 1 and can accept None.
On symbolic classes, ValueSpec objects are usually derived from
plain Python type annotations:
class A(pg.Object):
a: list[str]
b: dict = {'key': 'value'}
c: list | None
x: int
y: str | None
z: int | float
A bare ValueSpec instance is not a valid field annotation (static
type checkers cannot read it). When a field needs rules an annotation
cannot express, attach the spec via pg.field(value_spec=...):
Note that builtin container annotations (list[str], dict)
declare raw storage — assigned values stay plain list / dict —
while pg.List[str] / pg.Dict[str, int] annotations declare
symbolic storage.
value_type
abstractmethod
property
¶
Returns acceptable (resolved) value type(s).
fast_apply_info
abstractmethod
property
¶
Hot-path metadata describing whether apply() may be skipped.
Concrete specs return a FastApplyInfo with
is_eligible=True and the exact value_type when:
apply(v)is a no-op for values wheretype(v) is value_type;- no transform is set;
- the spec is not frozen;
- neither
_applynor_validateperforms work at runtime.
Otherwise specs return a FastApplyInfo() with
is_eligible=False (typically a shared module-level sentinel).
Schema and container specs (List/Tuple/Dict) consult this to bypass
the full apply pipeline when type identity already implies
validity. See FastApplyInfo for the bulk-check helper.
forward_refs
abstractmethod
property
¶
forward_refs: set[ForwardRef]
Returns forward references used by the value spec.
is_noneable
abstractmethod
property
¶
Returns True if current value spec accepts None.
default
abstractmethod
property
¶
Returns the default value.
If no default is provided, MISSING_VALUE will be returned for non-dict types. For Dict type, a dict that may contains nested MISSING_VALUE will be returned.
When a default_factory is configured (and no static default),
this property returns MISSING_VALUE. Use materialize_default
to obtain a per-instance value.
default_factory
abstractmethod
property
¶
Returns the zero-arg factory used to materialize defaults, or None.
annotation
abstractmethod
property
¶
Returns PyType annotation. MISSING_VALUE if annotation is absent.
transform
abstractmethod
property
¶
Returns a transform that will be applied on the input before apply.
noneable
abstractmethod
¶
set_default
abstractmethod
¶
set_default(
default: Any,
use_default_apply: bool = True,
root_path: KeyPath | None = None,
) -> Self
Sets the default value and returns self.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
Any
|
Default value. |
required |
use_default_apply
|
bool
|
If True, invoke |
True
|
root_path
|
KeyPath | None
|
(Optional) The path of the field. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
ValueSpec itself. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If default value cannot be applied when use_default_apply is set to True. |
Source code in pygx/typing/_class_schema.py
set_default_factory
abstractmethod
¶
Sets a zero-arg factory called whenever a default is materialized.
Stdlib-dataclasses-style: the factory is invoked once per default
materialization (not once per spec construction), so factories like
lambda: time.time() produce a fresh value each time. The factory
result is validated through apply on each call.
Setting default_factory clears any static default. Setting it to
None clears the factory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable, or None to clear. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
ValueSpec itself. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in pygx/typing/_class_schema.py
set_transform
abstractmethod
¶
Sets the user transform callable and returns self.
The transform runs on the raw input of apply, before type
validation; its result then re-enters the validation pipeline.
Source code in pygx/typing/_class_schema.py
materialize_default
abstractmethod
¶
Returns a per-instance default value.
If a default_factory is set, calls it and validates the result.
Otherwise returns a selective copy of the static default (via
copy_default, #664): recognized copyable shapes — builtin
containers, symbolic values, dataclasses — are deep-copied per
instance, while arbitrary-type templates are shared by reference.
Returns MISSING_VALUE when no default is configured.
With allow_partial=True, factory-only specs return a typed
MissingValue instead of invoking the factory — used by
partial-apply paths (e.g. schema auto-default generation) so the
factory only fires during real instance construction.
Source code in pygx/typing/_class_schema.py
freeze
abstractmethod
¶
Sets the default value using a permanent value and freezes current spec.
A frozen value spec will not accept any value that is not the default value. A frozen value spec is useful when a subclass fixes the value of a symbolic attribute and wants to prevent it from being modified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
permanent_value
|
Any
|
A permanent value used for current spec. If MISSING_VALUE, freeze the value spec with current default value. |
MISSING_VALUE
|
apply_before_use
|
bool
|
If True, invoke |
True
|
Returns:
| Type | Description |
|---|---|
Self
|
ValueSpec itself. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the current default value is |
Source code in pygx/typing/_class_schema.py
is_compatible
abstractmethod
¶
is_compatible(other: ValueSpec) -> bool
Returns True if values acceptable to other is acceptable to this spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
ValueSpec
|
Other value spec. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if values that is applicable to the other value spec can be applied to current spec. Otherwise False. |
Source code in pygx/typing/_class_schema.py
extend
abstractmethod
¶
extend(base: ValueSpec) -> Self
Extends a base spec with current spec's rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
ValueSpec
|
Base ValueSpec to extend. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
ValueSpec itself. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When this value spec cannot extend from base. |
Source code in pygx/typing/_class_schema.py
apply
abstractmethod
¶
apply(
value: Any,
allow_partial: bool = False,
child_transform: None | Callable[[KeyPath, Field, Any], Any] = None,
root_path: KeyPath | None = None,
inplace: bool = True,
) -> Any
Validates, completes and transforms the input value.
Here is the procedure of apply:
(1) If the spec is frozen, only the default value (or a missing
value) is accepted; the frozen default is returned.
(2) If the input is MISSING_VALUE, raise "Required value is not
specified" — unless `allow_partial` is True, in which case a
MissingValue placeholder is returned.
(3) If the input is None, accept it iff the spec is noneable;
otherwise raise ValueError.
(4) If the input is a CustomTyping instance, let its custom_apply
intercept: it either returns the final value directly or asks
to continue with the standard pipeline.
(5) If a user transform is set, call it on the input value; its
result re-enters the pipeline (without the transform).
(6) Check the value type against value_spec.value_type. On a
mismatch, attempt the implicit coercions — the universal
int -> float widening and the target type's __pg_accept__
classmethod — unless the spec is strict; raise TypeError when
none accepts the value.
(7) Run type-specific validation and completion (numeric bounds,
regex, enum membership, callable signature checks, ...).
Container specs such as Dict, List and Tuple recurse into
child values via their child specs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value to apply. |
required |
allow_partial
|
bool
|
If True, partial value is allowed. This is useful for container types (dict, list, tuple). |
False
|
child_transform
|
None | Callable[[KeyPath, Field, Any], Any]
|
Function to transform child node values into final values. (NOTE: This transform will not be performed on current value. Instead transform on current value is done by Field.apply, which has adequate information to call transform with both KeySpec and ValueSpec). |
None
|
root_path
|
KeyPath | None
|
Key path of current node. |
None
|
inplace
|
bool
|
If False, containers are validated on a copy so the caller's input is left untouched; verbatim values apply does not recurse into keep their identity. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
Final value:
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If additional key is found in value, or required key is missing and allow_partial is set to False. |
TypeError
|
If type of value is not the same as spec required. |
ValueError
|
If value is not acceptable, or value is MISSING_VALUE while allow_partial is set to False. |
Source code in pygx/typing/_class_schema.py
from_annotation
classmethod
¶
from_annotation(
annotation: Any,
auto_typing: bool = False,
accept_value_as_annotation: bool = False,
parent_module: ModuleType | None = None,
) -> ValueSpec
Gets a concrete ValueSpec from annotation.
Source code in pygx/typing/_class_schema.py
to_json_schema
¶
to_json_schema(
*,
include_type_name: bool = True,
include_subclasses: bool = False,
inline_nested_refs: bool = False,
**kwargs
) -> dict[str, Any]
Converts this field to JSON schema.
Source code in pygx/typing/_class_schema.py
from_json_schema
classmethod
¶
from_json_schema(
json_schema: dict[str, Any],
class_fn: Callable[[str, Schema], type[Any]] | None = None,
add_json_schema_as_metadata: bool = False,
) -> ValueSpec
Converts a JSON schema to a value spec.
Source code in pygx/typing/_class_schema.py
CustomTyping
¶
Interface for values that take over a field's validation.
Instances of CustomTyping subclasses can be assigned to fields of
any ValueSpec, and take over ValueSpec.apply via the
custom_apply method.
As a result, CustomTyping makes the schema system extensible without modifying
existing value specs. For example, marker objects such as
pygx.oneof extend CustomTyping so they can sit
in any field regardless of its value spec.
custom_apply
abstractmethod
¶
custom_apply(
path: KeyPath,
value_spec: ValueSpec,
allow_partial: bool,
child_transform: None | Callable[[KeyPath, Field, Any], Any] = None,
) -> tuple[bool, Any]
Custom apply on a value based on its original value spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
KeyPath
|
KeyPath of current object under its object tree. |
required |
value_spec
|
ValueSpec
|
Original value spec for this field. |
required |
allow_partial
|
bool
|
Whether allow partial object to be created. |
required |
child_transform
|
None | Callable[[KeyPath, Field, Any], Any]
|
Function to transform child node values into their final values. Transform function is called on leaf nodes first, then on their parents, recursively. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[bool, Any]
|
A tuple (proceed_with_standard_apply, value_to_proceed). If proceed_with_standard_apply is set to False, value_to_proceed will be used as final value. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the value is not compatible with the value spec. |
Source code in pygx/typing/_custom_typing.py
DocStr
dataclass
¶
DocStr(
style: DocStrStyle,
short_description: str | None,
long_description: str | None,
examples: list[DocStrExample],
args: dict[str, DocStrArgument],
returns: DocStrReturns | None,
raises: list[DocStrRaises],
blank_after_short_description: bool = True,
)
A docstring parsed into its structured parts.
Produced by DocStr.parse / docstr — carries the description,
arguments, returns, raises and examples sections as typed entries.
parameter
¶
parameter(param: Parameter) -> DocStrArgument | None
Returns doc str for an inspected parameter.
Source code in pygx/typing/_docstr.py
parse
classmethod
¶
parse(text: str, style: DocStrStyle | None = None) -> DocStr
Parses a docstring.
Source code in pygx/typing/_docstr.py
DocStrArgument
dataclass
¶
DocStrExample
dataclass
¶
DocStrRaises
dataclass
¶
DocStrReturns
dataclass
¶
DocStrStyle
¶
Bases: Enum
Docstring style.
ConstStrKey
¶
Bases: KeySpecBase, StrKey
Class that represents a constant string key.
Example:
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
string value of this key. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If key contains dots ('.'), which is not allowed. |
Source code in pygx/typing/_key_specs.py
ListKey
¶
Bases: NonConstKey
Class that represents key specification for a list.
Matches int keys (zero-based list indices) in [min_value,
max_value) — max_value is the exclusive upper bound, i.e. the
list size.
Example:
# Create a key spec for list indices in range [1, 5).
key = pg.typing.ListKey(min_value=1, max_value=5)
assert key.match(1)
assert key.match(4)
assert not key.match(5)
assert not key.match(0)
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_value
|
int
|
Minimum acceptable list index (inclusive). |
0
|
max_value
|
int | None
|
Exclusive upper bound for the list index (i.e. the list
size). |
None
|
Source code in pygx/typing/_key_specs.py
max_value
property
¶
Returns the exclusive upper bound of acceptable list indices.
extend
¶
extend(base: KeySpec) -> Self
Extend current key spec on top of base spec.
Source code in pygx/typing/_key_specs.py
match
¶
Returns whether this key spec can match against input key.
Source code in pygx/typing/_key_specs.py
format
¶
Format this object.
Source code in pygx/typing/_key_specs.py
NonConstKey
¶
Bases: KeySpecBase
Base class of specification for non-const keys.
A non-const key spec matches a family of keys (e.g. all string keys matching a regular expression) rather than one fixed key.
Subclasses: pygx.typing.StrKey,
pygx.typing.ListKey,
pygx.typing.TupleKey.
StrKey
¶
Bases: NonConstKey
Class that represents a variable string key.
Used as the key spec of a field (e.g. in a
pygx.typing.Dict schema) to declare a wildcard
field that matches a family of string keys instead of a single name.
Matches any string key when no regex is given. With a regex,
a key matches if re.match succeeds — the pattern is anchored at
the start of the key only, so StrKey('foo') also matches
'foobar'; end the pattern with $ to require a full match.
Non-string keys never match.
Example:
# Create a key spec that specifies all string keys started with 'foo'.
key = pg.typing.StrKey('foo.*')
assert key.match('foo')
assert key.match('foo1')
assert not key.match('bar')
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
regex
|
str | None
|
An optional regular expression. If set to None, any string value is acceptable. |
None
|
Source code in pygx/typing/_key_specs.py
TupleKey
¶
Bases: NonConstKey
Class that represents a key specification for tuple.
Example:
# Create a key spec that specifies item 0 of a tuple.
key = pg.typing.TupleKey(0)
assert key.match(0)
assert not key.match(1)
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | None
|
index of the tuple field that this key spec applies to. If None, this tuple value spec applies to all elements of a variable-length tuple. |
None
|
Source code in pygx/typing/_key_specs.py
extend
¶
extend(base: KeySpec) -> Self
Extends this key spec on top of a base spec.
Source code in pygx/typing/_key_specs.py
match
¶
format
¶
Format this object.
Date
¶
Date(
default: date | None = MISSING_VALUE,
default_factory: Callable[[], date | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: _StdlibScalar
Value spec for datetime.date.
Lax coercion: ISO-8601 date strings. A datetime.datetime value is
REJECTED (Pydantic parity — no silent time truncation), even though
datetime subclasses date.
Examples:
Source code in pygx/typing/_stdlib_specs.py
Datetime
¶
Datetime(
default: datetime | None = MISSING_VALUE,
default_factory: Callable[[], datetime | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: _StdlibScalar
Value spec for datetime.datetime.
Lax coercion (Pydantic parity): ISO-8601 strings, int/float POSIX
timestamps (tz-aware UTC), and datetime.date (midnight). Strict
mode accepts only datetime.datetime instances.
Examples:
# A required datetime.
pg.typing.Datetime()
# With a default.
pg.typing.Datetime(default=datetime.datetime(2026, 1, 1))
# ISO-8601 strings (and POSIX timestamps) coerce.
spec = pg.typing.Datetime()
assert spec.apply('2026-01-01T00:00:00') == datetime.datetime(2026, 1, 1)
Source code in pygx/typing/_stdlib_specs.py
Decimal
¶
Decimal(
default: Decimal | None = MISSING_VALUE,
default_factory: Callable[[], Decimal | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: _StdlibScalar
Value spec for decimal.Decimal.
Lax coercion: strings, ints, and floats — floats convert through
their str form (1.5 → Decimal('1.5'), no binary artifacts,
Pydantic parity). A non-finite coercion RESULT (NaN/inf) is rejected;
an exact Decimal value is accepted verbatim.
Examples:
Source code in pygx/typing/_stdlib_specs.py
Path
¶
Path(
default: Path | None = MISSING_VALUE,
default_factory: Callable[[], Path | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: _StdlibScalar
Value spec for pathlib.Path.
Lax coercion: strings (pathlib.Path(value)).
Examples:
Source code in pygx/typing/_stdlib_specs.py
Time
¶
Time(
default: time | None = MISSING_VALUE,
default_factory: Callable[[], time | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: _StdlibScalar
Value spec for datetime.time.
Lax coercion: ISO-8601 time strings, and int/float seconds since
midnight in [0, 86400) — producing a tz-aware UTC time, exactly as
Pydantic v2 does.
Examples:
Source code in pygx/typing/_stdlib_specs.py
Timedelta
¶
Timedelta(
default: timedelta | None = MISSING_VALUE,
default_factory: Callable[[], timedelta | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: _StdlibScalar
Value spec for datetime.timedelta.
Lax coercion: int/float seconds and ISO-8601 duration strings
('PT90S', 'P1DT2H', ...) — the same form the wire emits.
Examples:
Source code in pygx/typing/_stdlib_specs.py
Uuid
¶
Uuid(
default: UUID | None = MISSING_VALUE,
default_factory: Callable[[], UUID | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: _StdlibScalar
Value spec for uuid.UUID.
Lax coercion: canonical/hex UUID strings and 16-byte values.
Examples:
Source code in pygx/typing/_stdlib_specs.py
Convertible
¶
Runtime stub: Convertible[T, S] evaluates to T.
Any
¶
Any(
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
annotation: Any = MISSING_VALUE,
transform: None | Callable[[Any], Any] = None,
frozen: bool = False,
strict: bool | None = None,
)
Bases: ValueSpecBase
Value spec for any type.
Accepts values of any type, including None — an Any spec is
always noneable. "Required" here means only that a value (possibly
None) must be provided when the spec has no default.
Examples:
# A required value of any type.
pg.typing.Any()
# An optional value of any type, with None as its default value.
pg.typing.Any().noneable()
# A value of any type, with 1 as its default value.
pg.typing.Any(default=1)
Note
While Any type is very flexible and useful to pass though data between components, we should minimize its usage since minimal validation is performed on this type.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
Any
|
(Optional) default value of this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
annotation
|
Any
|
(Optional) external provided type annotation. |
MISSING_VALUE
|
transform
|
None | Callable[[Any], Any]
|
(Optional) user-defined function to be called on the input
of |
None
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Bool
¶
Bool(
default: bool | None = MISSING_VALUE,
default_factory: Callable[[], bool | None] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: PrimitiveType
Value spec for boolean type.
Accepts exactly bool values — there is no implicit coercion from
int (pg.typing.Bool().apply(1) raises TypeError).
Examples:
# A required bool value.
pg.typing.Bool()
# A bool value with the default value set to True.
pg.typing.Bool(default=True)
# An optional bool value with default value set to None.
pg.typing.Bool().noneable()
# An optional bool value with default value set to True.
pg.typing.Bool(default=True).noneable()
# A frozen bool with value set to True that is not modifiable by subclasses.
pg.typing.Bool().freeze(True)
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
bool | None
|
Default value for the value spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], bool | None] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
Callable
¶
Callable(
args: list[ValueSpecOrAnnotation] | None = None,
kw: None | list[tuple[str, ValueSpecOrAnnotation]] = None,
returns: ValueSpecOrAnnotation | None = None,
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
transform: None | Callable[[Any], Callable[..., Any]] = None,
callable_type: type[Any] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Generic, ValueSpecBase
Value spec for callable.
A value must be callable. When args / kw / returns are
provided, the value's signature is checked for compatibility at
apply time: the callable must accept the declared number of
positional arguments (its own *args absorbs extras) and every
declared keyword name (its own **kwargs absorbs unknown names).
When the callable's parameters carry value specs of their own (e.g. a
functor created via pygx.symbolize with
explicit field definitions), the declared arg/return specs are also
checked against them; plain Python type annotations on the callable
are not converted, so they are not checked. Incompatibility raises
TypeError.
Examples:
# A required callable object with any args.
pg.typing.Callable()
# An optional callable objects with the first argument as int, and the
# second argument as float. The field has None as its default value.
pg.typing.Callable([pg.typing.Int(), pg.typing.Float()]).noneable()
# A callable object that has its first argument as int, and has keyword
# arguments 'x' (any type), 'y' (a str) and return value as int.
pg.typing.Callable(
[pg.typing.Int()],
kw=[
('x', pg.typing.Any()),
('y', pg.typing.Str())
],
returns=pg.typing.Int())
See also: pygx.typing.Functor.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
list[ValueSpecOrAnnotation] | None
|
(Optional) value specs for the callable's positional arguments. |
None
|
kw
|
None | list[tuple[str, ValueSpecOrAnnotation]]
|
(Optional) a list of (name, value spec) tuples for the callable's keyword arguments. |
None
|
returns
|
ValueSpecOrAnnotation | None
|
(Optional) value spec for the return value. |
None
|
default
|
Any
|
(Optional) default value of this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
transform
|
None | Callable[[Any], Callable[..., Any]]
|
(Optional) user-defined function to be called on the input
of |
None
|
callable_type
|
type[Any] | None
|
(Optional) a type the callable value must be an
instance of (e.g. |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 | |
forward_refs
¶
forward_refs() -> set[ForwardRef]
Returns forward references used in this spec.
Source code in pygx/typing/_value_specs.py
format
¶
Format this spec.
Source code in pygx/typing/_value_specs.py
Dict
¶
Dict(
schema: (
ValueSpec
| Schema
| dict[FieldKeyDef, FieldValueDef]
| list[Field | FieldDef]
| type[Any]
| None
) = None,
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
transform: None | Callable[[Any], dict[Any, Any]] = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
*,
symbolic: bool | None = None,
auto_wrap: bool = True
)
Bases: Generic, ValueSpecBase
Value spec for dict type.
Accepts dict values, validated against an optional schema: with no
schema, arbitrary key/value pairs are accepted; a value spec constrains
the values under arbitrary string keys; a field list / dict / TypedDict
class defines per-key fields — missing keys are filled from field
defaults, and keys matched by no field are rejected with KeyError.
Examples:
# A required dict of arbitrary keys and values.
pg.typing.Dict()
# An optional Dict of keys started with 'foo' and int values, with None as
# the default value.
pg.typing.Dict([
(pg.typing.StrKey(), pg.typing.Int())
]).noneable()
# A dict with two keys ('x' and 'y').
pg.typing.Dict([
('x', pg.typing.Float()),
('y', pg.typing.Int(min_value=1))
])
# A dict with a user validator.
def validate_sum(d):
if sum(d.values()) > 1.:
raise ValueError('The sum of the dict values should be less than 1.')
pg.typing.Dict([
(pg.typing.StrKey(), pg.typing.Float())
], transform=validate_sum)
# A frozen dict that prevents subclass to extend/override.
pg.typing.Dict([
('x', 1),
('y', 2.0)
]).freeze()
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
ValueSpec | Schema | dict[FieldKeyDef, FieldValueDef] | list[Field | FieldDef] | type[Any] | None
|
(Optional) a Schema object for this Dict, or a dict of field key
to field value definition, or a list of field definitions, or a
TypedDict class, or a value spec.
If None, it specifies a schema-less Dict that may accept arbitrary
key/value pairs.
If a TypedDict class, it specifies a closed Dict whose const fields
mirror the TypedDict's keys (extra keys are rejected; optional keys
become noneable fields defaulting to None).
If a value spec, it specifies a Dict that may accept arbitrary keys with
values constrained by the value spec.
A field definition is a tuple of
( |
None
|
default
|
Any
|
Default value. If MISSING_VALUE, the default value will be computed according to the schema. |
MISSING_VALUE
|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
transform
|
None | Callable[[Any], dict[Any, Any]]
|
(Optional) user-defined function to be called on the input
of |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
symbolic
|
bool | None
|
Tri-state storage declaration, normally authored by a
field annotation rather than passed directly. |
None
|
auto_wrap
|
bool
|
Whether a raw |
True
|
Source code in pygx/typing/_value_specs.py
3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 | |
symbolic
property
¶
Storage declaration: True stores a symbolic pg.Dict,
False a raw dict, None when no annotation declared
storage.
noneable
¶
Dict-specific noneable: replaces the default with None.
Unlike the base noneable, turning noneable on sets the default
to None even when a default (e.g. one generated from the
schema) already exists; turning it off regenerates the
schema-based default.
Source code in pygx/typing/_value_specs.py
forward_refs
¶
forward_refs() -> set[ForwardRef]
Returns forward references used in this spec.
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Enum
¶
Enum(
values: list[Any],
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Generic, PrimitiveType
Value spec for enum type.
An applied value must equal one of the candidate values, which may
mix types. A None among the values makes the spec noneable (and
noneable adds/removes None from the candidate list). The default,
when given, must be one of the candidates.
Examples:
# A str enum value with options 'a', 'b', 'c' and its default set to 'a'.
pg.typing.Enum(['a', 'b', 'c'], 'a')
# A mixed-type enum value.
pg.typing.Enum(['a', 5, True], 'a')
# An optional enum value with default value set to 'a'.
pg.typing.Enum(['a', 'b', 'c'], 'a').noneable()
# A frozen enum with value set to 'a' that is not modifiable by subclasses.
pg.typing.Enum(['a', 'b', 'c'], 'a').freeze('a')
# Values outside the candidate list are rejected (raises ValueError).
# pg.typing.Enum(['a', 'b'], 'a').apply('c')
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
list[Any]
|
all acceptable values. |
required |
default
|
Any
|
default value for this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
noneable
¶
Enum-specific noneable: edits the candidate list.
Turning noneable on appends None to values (when absent);
turning it off removes None (and clears a None default).
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Float
¶
Float(
default: float | None = MISSING_VALUE,
default_factory: Callable[[], float | None] | None = None,
min_value: float | None = None,
max_value: float | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
gt: float | None = None,
ge: float | None = None,
lt: float | None = None,
le: float | None = None,
)
Bases: Number
Value spec for float type.
Accepts float values; an int (or bool) input is widened to
float unless strict=True. min_value / max_value bounds
are inclusive.
Examples:
# A required float value.
pg.typing.Float()
# A required float value with min and max value (both inclusive.)
pg.typing.Float(min_value=1.0, max_value=10.0)
# A float value with the default value set to 1
pg.typing.Float(default=1)
# An optional float value with default value set to None.
pg.typing.Float().noneable()
# An optional float value with default value set to 1.0.
pg.typing.Float(default=1.0).noneable()
# A frozen float with value set to 1.0 that is not modifiable by subclasses.
pg.typing.Float().freeze(1)
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
float | None
|
(Optional) default value for this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], float | None] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
min_value
|
float | None
|
(Optional) minimum value of acceptable values. |
None
|
max_value
|
float | None
|
(Optional) maximum value of acceptable values. |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
gt
|
float | None
|
Exclusive lower bound (#522, pydantic spelling) — on Int it
rewrites to |
None
|
ge
|
float | None
|
Inclusive lower bound — synonym of |
None
|
lt
|
float | None
|
Exclusive upper bound — Int rewrite |
None
|
le
|
float | None
|
Inclusive upper bound — synonym of |
None
|
Source code in pygx/typing/_value_specs.py
Functor
¶
Functor(
args: list[ValueSpecOrAnnotation] | None = None,
kw: None | list[tuple[str, ValueSpecOrAnnotation]] = None,
returns: ValueSpecOrAnnotation | None = None,
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
transform: None | Callable[[Any], Callable[..., Any]] = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Callable
Value spec for Functor.
Same as pygx.typing.Callable, except that
only pygx.Functor instances (created via
pygx.functor or
pygx.symbolize on a function) are
acceptable values.
Examples:
# A required PyGX functor with any args.
pg.typing.Functor()
# An optional functor with the first argument as int, and the second
# argument as float. The field has None as its default value.
pg.typing.Functor([pg.typing.Int(), pg.typing.Float()]).noneable()
# A functor that has its first argument as int, and has keyword
# arguments 'x' (any type), 'y' (a str) and return value as int.
pg.typing.Functor(
[pg.typing.Int()],
kw=[
('x', pg.typing.Any()),
('y', pg.typing.Str())
],
returns=pg.typing.Int())
See also: pygx.typing.Callable.
Constructor. Same as Callable.__init__, with callable_type
fixed to pg.Functor.
Source code in pygx/typing/_value_specs.py
Generic
¶
Base class for value specs that support [] subscripting.
Subscripting a subclass builds a spec instance from the type arguments, giving annotation-style shorthands for common specs:
assert pg.typing.Int[0, 10] == pg.typing.Int(min_value=0, max_value=10)
assert pg.typing.Str['foo.*'] == pg.typing.Str(regex='foo.*')
assert pg.typing.Enum['a', 'b'] == pg.typing.Enum(values=['a', 'b'])
GenericMeta
¶
Bases: ABCMeta
Metaclass that makes Generic subclasses subscriptable.
Routes Cls[...] to the class's with_type_args factory (e.g.
pg.typing.Int[0, 10] becomes pg.typing.Int(min_value=0,
max_value=10)).
GenericTypeAlias
¶
Bases: Generic
Base class for generic type aliases.
A generic type alias is subscript-only: Alias[...] expands to a
value spec built from other spec classes (it has no spec class of
its own), and the alias itself cannot be instantiated. Subclasses:
pygx.typing.Sequence,
pygx.typing.Optional.
Source code in pygx/typing/_value_specs.py
Inherit
¶
Sentinel annotation: inherit the parent field's value_spec.
Use in a pg.Object subclass to keep the parent's value spec
(including Enum / regex / numeric bounds / etc.) while overriding
only the field's default value — without restating the parent's
spec on the subclass. Static type checkers see Inherit as
typing.Any, so the subclass's default is honored by the
synthesized __init__ and the override is variance-friendly.
Example:
from typing import Annotated
class Parent(pg.Object):
model: Annotated[
str, pg.field(value_spec=pg.typing.Enum(['a', 'b']))
]
class Child(Parent):
model: pg.typing.Inherit = 'a' # inherits Enum, default='a'
Errors at class creation if there is no parent field with the same key, or if no default value is provided on the subclass.
Int
¶
Int(
default: int | None = MISSING_VALUE,
default_factory: Callable[[], int | None] | None = None,
min_value: int | None = None,
max_value: int | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
gt: int | None = None,
ge: int | None = None,
lt: int | None = None,
le: int | None = None,
)
Bases: Number
Value spec for int type.
Accepts int values; a bool also passes (it is an int
subclass) unless strict=True. min_value / max_value bounds
are inclusive; gt / ge / lt / le are pydantic-style
aliases for the bounds.
Examples:
# A required int value.
pg.typing.Int()
# A required int value with min and max value (both inclusive.)
pg.typing.Int(min_value=1, max_value=10)
# A int value with the default value set to 1
pg.typing.Int(default=1)
# An optional int value with default value set to None.
pg.typing.Int().noneable()
# An optional int value with default value set to 1.
pg.typing.Int(default=1).noneable()
# A frozen int with value set to 1 that is not modifiable by subclasses.
pg.typing.Int().freeze(1)
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
int | None
|
(Optional) default value for this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], int | None] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
min_value
|
int | None
|
(Optional) minimum value of acceptable values. |
None
|
max_value
|
int | None
|
(Optional) maximum value of acceptable values. |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
gt
|
int | None
|
Exclusive lower bound (#522, pydantic spelling) — on Int it
rewrites to |
None
|
ge
|
int | None
|
Inclusive lower bound — synonym of |
None
|
lt
|
int | None
|
Exclusive upper bound — Int rewrite |
None
|
le
|
int | None
|
Inclusive upper bound — synonym of |
None
|
Source code in pygx/typing/_value_specs.py
List
¶
List(
element_value: ValueSpecOrAnnotation,
default: list[Any] | None = MISSING_VALUE,
default_factory: Callable[[], list[Any] | None] | None = None,
min_size: int | None = None,
max_size: int | None = None,
size: int | None = None,
transform: None | Callable[[Any], list[Any]] = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
*,
min_length: int | None = None,
max_length: int | None = None,
symbolic: bool | None = None,
auto_wrap: bool = True
)
Bases: Generic, ValueSpecBase
Value spec for list type.
Accepts list values whose every element passes the
element_value spec; optional min_size / max_size (or an
exact size) bound the length.
Examples:
# A required non-negative integer list.
pg.typing.List(pg.typing.Int(min_value=0))
# An optional str list with 2-5 items.
pg.typing.List(pg.typing.Str(), min_size=2, max_size=5).noneable()
# A size-2 list of arbitrary types.
pg.typing.List(pg.typing.Any(), size=2)
# A frozen list that prevents subclass to extend/override.
pg.typing.List(pg.typing.Int()).freeze([1])
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element_value
|
ValueSpecOrAnnotation
|
A |
required |
default
|
list[Any] | None
|
(Optional) default value for this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], list[Any] | None] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
min_size
|
int | None
|
(Optional) min size of list. If None, 0 will be used. |
None
|
max_size
|
int | None
|
(Optional) max size of list. |
None
|
size
|
int | None
|
(Optional) size of List. A shortcut to specify min_size and max_size
at the same time. |
None
|
transform
|
None | Callable[[Any], list[Any]]
|
(Optional) user-defined function to be called on the input
of |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
min_length
|
int | None
|
Synonym of |
None
|
max_length
|
int | None
|
Synonym of |
None
|
symbolic
|
bool | None
|
Tri-state storage declaration, normally authored by a
field annotation (see |
None
|
auto_wrap
|
bool
|
Whether a raw |
True
|
Source code in pygx/typing/_value_specs.py
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 | |
symbolic
property
¶
Storage declaration: True stores a symbolic pg.List,
False a raw list, None when no annotation declared
storage.
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Number
¶
Number(
value_type: type[int] | type[float],
default: int | float | None = MISSING_VALUE,
default_factory: Callable[[], int | float | None] | None = None,
min_value: int | float | None = None,
max_value: int | float | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Generic, PrimitiveType
Base class for value spec of numeric types.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value_type
|
type[int] | type[float]
|
Type of number. |
required |
default
|
int | float | None
|
Default value for this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], int | float | None] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
min_value
|
int | float | None
|
(Optional) minimum acceptable value (inclusive). |
None
|
max_value
|
int | float | None
|
(Optional) maximum acceptable value (inclusive). |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Object
¶
Object(
t: type[Any] | ForwardRef | str,
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
transform: None | Callable[[Any], Any] = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Generic, ValueSpecBase
Value spec for object type.
Accepts instances of class t, subclasses included. Passing a class
name string creates a forward reference that is resolved when first
needed, allowing specs for classes not yet defined.
Examples:
# A required instance of class A and its subclasses.
pg.typing.Object(A)
# A required instance of class A and its subclasses (forward declaration).
pg.typing.Object('A')
# An optional instance of class A with None as its default value.
pg.typing.Object(A).noneable()
# An instance of class A with default value.
pg.typing.Object(A, default=A())
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
type[Any] | ForwardRef | str
|
Class of the object. Objects of subclass of this class is acceptable. |
required |
default
|
Any
|
(Optional) default value of this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
transform
|
None | Callable[[Any], Any]
|
(Optional) user-defined function to be called on the input
of |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Optional
¶
Bases: GenericTypeAlias
Type alias: Optional[T] is the spec of T marked noneable.
Source code in pygx/typing/_value_specs.py
PrimitiveType
¶
PrimitiveType(
value_type: type[Any] | tuple[type[Any], ...] | None,
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: ValueSpecBase
Base class of value specification for primitive types.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value_type
|
type[Any] | tuple[type[Any], ...] | None
|
Acceptable value type(s). |
required |
default
|
Any
|
Default value. |
MISSING_VALUE
|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
Sequence
¶
Bases: GenericTypeAlias
Type alias: Sequence[T] accepts a list OR a tuple of T.
spec = pg.typing.Sequence[int]
assert spec == pg.typing.Union(
[pg.typing.List(pg.typing.Int()), pg.typing.Tuple(pg.typing.Int())]
)
Source code in pygx/typing/_value_specs.py
Str
¶
Str(
default: str | None = MISSING_VALUE,
default_factory: Callable[[], str | None] | None = None,
regex: str | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Generic, PrimitiveType
Value spec for string type.
Accepts str values. An optional regex is validated with
re.match — anchored at the start of the string only, so end the
pattern with $ to require a full match.
Examples:
# A required str value.
pg.typing.Str()
# A required str value which matches with a regular expression.
pg.typing.Str(regex='foo.*')
# A str value with the default value set to 'foo'.
pg.typing.Str(default='foo')
# An optional str value with default value set to None.
pg.typing.Str().noneable()
# An optional str value with default value set to 'foo'.
pg.typing.Str(default='foo').noneable()
# A frozen str with value set to 'foo' that is not modifiable by subclasses.
pg.typing.Str().freeze('foo')
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
str | None
|
Default value for this value spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], str | None] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
regex
|
str | None
|
Optional regular expression for acceptable value, matched
with |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Tuple
¶
Tuple(
element_values: ValueSpecOrAnnotation | Sequence[ValueSpecOrAnnotation],
default: tuple[Any, ...] | None = MISSING_VALUE,
default_factory: Callable[[], tuple[Any, ...] | None] | None = None,
min_size: int | None = None,
max_size: int | None = None,
size: int | None = None,
transform: None | Callable[[Any], tuple[Any, ...]] = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
*,
min_length: int | None = None,
max_length: int | None = None
)
Bases: Generic, ValueSpecBase
Value spec for tuple type.
Accepts tuple values, in two flavors. The fixed-length form (a
sequence of element specs) validates each position against its own
spec and requires an exact length; the variable-length form (a single
element spec) validates every element against it, with optional
min_size / max_size bounds.
Examples:
# A required tuple with 2 items which are non-negative integers.
pg.typing.Tuple([pg.typing.Int(min_value=0), pg.typing.Int(min_value=0)])
# An optional int tuple of size 3 with None as its default value.
pg.typing.Tuple(pg.typing.Int(), size=3).noneable()
# A int tuple with minimal size 1 and maximal size 5.
pg.typing.Tuple(pg.typing.Int(), min_size=1, max_size=5)
# A (int, float) tuple with default value (1, 1.0).
pg.typing.Tuple([pg.typing.Int(), pg.typing.Float()], default=(1, 1.0))
# A frozen tuple that prevents subclass to extend/override.
pg.typing.Tuple(pg.typing.Int()).freeze((1,))
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element_values
|
ValueSpecOrAnnotation | Sequence[ValueSpecOrAnnotation]
|
A ValueSpec object or its equivalence as the element spec for a variable-length tuple, or a sequence of ValueSpec objects or their equivalences as the elements specs for a fixed-length tuple. |
required |
default
|
tuple[Any, ...] | None
|
(Optional) default value for this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], tuple[Any, ...] | None] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
min_size
|
int | None
|
(Optional) min size of tuple. If None, 0 will be used. Applicable only for variable-length tuple. |
None
|
max_size
|
int | None
|
(Optional) max size of tuple. Applicable only for variable-length tuple. |
None
|
size
|
int | None
|
(Optional) size of tuple. A shortcut to specify min_size and
max_size at the same time. |
None
|
transform
|
None | Callable[[Any], tuple[Any, ...]]
|
(Optional) user-defined function to be called on the input
of |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
min_length
|
int | None
|
Synonym of |
None
|
max_length
|
int | None
|
Synonym of |
None
|
Source code in pygx/typing/_value_specs.py
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 | |
forward_refs
¶
forward_refs() -> set[ForwardRef]
Returns forward references used in this spec.
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Type
¶
Type(
t: type[Any] | str,
default: type[Any] = MISSING_VALUE,
default_factory: Callable[[], type[Any]] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Generic, ValueSpecBase
Value spec for type.
Accepts type objects that are t itself or one of its subclasses.
Like Object, a class name string creates a forward reference resolved
when first needed.
Examples:
# A required type or subclass of A.
pg.typing.Type(A)
# A required type or subclass of A (forward declaration).
pg.typing.Type('A')
# An optional type or subclass of A.
pg.typing.Type(A).noneable()
# A required type or subclass of A with default value B
# (B is a subclass of A).
pg.typing.Type(A, default=B)
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
type[Any] | str
|
The base type, or a string as a forward reference to it.
Applied values must be |
required |
default
|
type[Any]
|
(Optional) default type for this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], type[Any]] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Union
¶
Union(
candidates: Sequence[ValueSpecOrAnnotation],
default: Any = MISSING_VALUE,
default_factory: Callable[[], Any] | None = None,
is_noneable: bool = False,
frozen: bool = False,
strict: bool | None = None,
)
Bases: Generic, ValueSpecBase
Value spec for Union.
A value is accepted when one of the candidate specs accepts it.
Candidates are matched in declaration order: a value whose type matches
a candidate is validated by that candidate; otherwise each candidate in
turn is asked to coerce the value through its own apply (e.g. an
int widens through a Float candidate), and the first success
wins. If no candidate accepts, TypeError is raised. A union may
not contain two candidates of the same spec type for the same value
type (e.g. two Int candidates); two Object candidates of
different classes are fine.
Examples:
# A required int or float value.
pg.typing.Union([pg.typing.Int(), pg.typing.Float()])
# An optional int or float value with default set to None.
pg.typing.Union([pg.typing.Int(), pg.typing.Float()]).noneable()
# A dict of specific keys, instance of class A or B, with {x=1} as its
# default value.
pg.typing.Union([
pg.typing.Dict([
('x', pg.typing.Int(min_value=1)),
]),
pg.typing.Object(A),
pg.typing.Object(B),
], default={'x': 1})
Values are dispatched to the matching candidate; a mismatched type is coerced by the first candidate that accepts it:
spec = pg.typing.Union([pg.typing.Str(), pg.typing.Float()])
assert spec.apply('a') == 'a'
assert spec.apply(1) == 1.0 # Widened by the Float candidate.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidates
|
Sequence[ValueSpecOrAnnotation]
|
A sequence of value spec objects or their equivalence as the spec for candidate types. |
required |
default
|
Any
|
(Optional) default value of this spec. |
MISSING_VALUE
|
default_factory
|
Callable[[], Any] | None
|
Zero-arg callable invoked once per default
materialization. Mutually exclusive with |
None
|
is_noneable
|
bool
|
(Optional) If True, None is acceptable for this spec. |
False
|
frozen
|
bool
|
If True, values other than the default value are not acceptable. |
False
|
strict
|
bool | None
|
If True, reject implicit conversions (strict mode); None
(default) inherits the class-wide |
None
|
Source code in pygx/typing/_value_specs.py
4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 | |
forward_refs
¶
forward_refs() -> set[ForwardRef]
Returns forward references used in this spec.
Source code in pygx/typing/_value_specs.py
noneable
¶
Union-specific noneable: propagates to every candidate.
Besides marking the union itself, each candidate spec is marked
noneable (or not) as well, so None is acceptable no matter
which candidate handles the value.
Source code in pygx/typing/_value_specs.py
get_candidate
¶
Get candidate by a destination value spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dest_spec
|
ValueSpec
|
destination value spec which is a superset of the value spec to return. E.g. Any (dest_spec) is superset of Int (child spec). |
required |
Returns:
| Type | Description |
|---|---|
ValueSpec | None
|
The first value spec under Union with which the destination value spec is compatible. |
Source code in pygx/typing/_value_specs.py
is_compatible
¶
is_compatible(other: ValueSpec) -> bool
Union specific compatibility check.
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
CallableWithOptionalKeywordArgs
¶
Wraps a callable, dropping keyword args it does not accept.
Calls delegate to func, with any keyword listed in
optional_keywords that is absent from func's signature silently
removed. Useful for invoking user callbacks that may or may not declare
an optional keyword.
Example:
f = pg.typing.CallableWithOptionalKeywordArgs(lambda x: x ** 2, ['y'])
assert f(2, y=3) == 4 # Keyword 'y' is ignored.
Source code in pygx/typing/_callable_ext.py
PresetArgValue
¶
Bases: Formattable
Marker default for arguments whose values may come from presets.
Used as an argument's default value in a function decorated with
enable_preset_args: when the caller omits the argument, its value is
taken from the enclosing preset_args context, falling back to
default when no preset provides it.
Example:
@pg.typing.enable_preset_args()
def foo(x, y=pg.typing.PresetArgValue(default=1)):
return x + y
with pg.typing.preset_args(dict(y=2)):
print(foo(x=1)) # 3: y=2
print(foo(x=1)) # 2: y=1
Source code in pygx/typing/_callable_ext.py
inspect
classmethod
¶
inspect(func: FunctionType) -> dict[str, PresetArgValue]
Gets the PresetArgValue specified in a function's signature.
Source code in pygx/typing/_callable_ext.py
resolve_args
classmethod
¶
resolve_args(
call_args: Sequence[Any],
call_kwargs: dict[str, Any],
positional_arg_names: Sequence[str],
arg_defaults: dict[str, Any],
preset_kwargs: dict[str, Any],
include_all_preset_kwargs: bool = False,
) -> tuple[Sequence[Any], dict[str, Any]]
Resolves calling arguments passed to a method with presets.
Source code in pygx/typing/_callable_ext.py
cached_property
¶
Bases: property, Generic[_T]
Property-typed view of functools.cached_property.
Pyright sees this as a property[_T] subclass so overrides of
@property-typed base attributes type-check. At runtime the
bound name is functools.cached_property (see the else
branch); this class is never instantiated.
Source code in pygx/typing/_typing_compat.py
annotation_from_str
¶
Parses a type annotation from its string form.
Example:
BNF for PyType annotations:
<maybe_union> ::= <type> | <type> "|" <maybe_union>
<type> ::= <literal_type> | <non_literal_type>
<literal_type> ::= "Literal" <literal_params>
<literal_params> ::= "[" <python_values> "]"
(parsed by `pg.coding.evaluate`)
<non_literal_type> ::= <type_id> | <type_id> "[" <type_arg> "]"
<type_arg> ::= <maybe_type_list>
| <maybe_type_list> "," <maybe_type_list>
<maybe_type_list> ::= "[" <type_arg> "]" | <maybe_union>
<type_id> ::= 'aAz_.1-9'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation_str
|
str
|
String form of type annotations. E.g. "list[str]". |
required |
parent_module
|
ModuleType | None
|
The module where the annotation was defined, used to resolve non-builtin names. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Object form of the annotation. |
Raises:
| Type | Description |
|---|---|
SyntaxError
|
If the annotation string is invalid. |
Source code in pygx/typing/_annotation_conversion.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
validate
¶
validate(
value: Any,
annotation: Any,
*,
allow_partial: bool = False,
parent_module: ModuleType | None = None
) -> Any
Validates a bare value against a type annotation, in one line.
The TypeAdapter analog for pydantic migrants: converts annotation
into a value spec (cached per annotation) and applies it to value —
type-checking, running registered coercions (e.g. int → float),
and filling schema defaults — without hand-building the spec:
pg.validate([1, 2], list[int]) # -> [1, 2]
pg.validate({'x': 1}, dict[str, int]) # -> {'x': 1}
pg.validate(None, int | None) # -> None
pg.validate([1, 'x'], list[int]) # TypeError (path=[1])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value to validate. Never mutated — containers are validated
on a copy ( |
required |
annotation
|
Any
|
A type annotation ( |
required |
allow_partial
|
bool
|
If True, missing required values are filled with
|
False
|
parent_module
|
ModuleType | None
|
The module whose namespace resolves string forward
references in |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The validated (possibly coerced / default-filled) value. |
Raises:
| Type | Description |
|---|---|
TypeError
|
The value (or a nested element, path-prefixed) does not
match the annotation — or the annotation contains a forward
reference that does not resolve at call time (a typo'd string, or
a missing |
ValueError
|
A value-level constraint fails (e.g. |
KeyError
|
A mapping value carries a key its schema does not allow
(the |
Source code in pygx/typing/_annotation_conversion.py
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 | |
schema
¶
schema(
cls_or_fn: Callable[..., Any],
args: (
list[Field | FieldDef] | dict[FieldKeyDef, FieldValueDef] | None
) = None,
returns: ValueSpec | None = None,
*,
auto_typing: bool = True,
auto_doc: bool = True,
remove_self: bool = True,
include_return: bool = False
) -> Schema
Returns the schema from the signature of a class or a function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls_or_fn
|
Callable[..., Any]
|
A class or a function. |
required |
args
|
list[Field | FieldDef] | dict[FieldKeyDef, FieldValueDef] | None
|
(Optional) additional annotations for arguments. |
None
|
returns
|
ValueSpec | None
|
(Optional) additional annotation for return value. |
None
|
auto_typing
|
bool
|
If True, enable type inference from annotations. |
True
|
auto_doc
|
bool
|
If True, extract schema/field descriptions from docstrings. |
True
|
remove_self
|
bool
|
If True, remove the first |
True
|
include_return
|
bool
|
If True, include the return value spec in the schema under the key 'return'. |
False
|
Returns:
| Type | Description |
|---|---|
Schema
|
A pg.typing.Schema object. |
Source code in pygx/typing/_callable_signature.py
signature
¶
signature(
func: Callable[..., Any], auto_typing: bool = True, auto_doc: bool = True
) -> Signature
Gets the signature from a Python callable.
Source code in pygx/typing/_callable_signature.py
copy_default
¶
Selective per-instance copy of a static default (Pydantic-aligned, #664).
The rule (owner ruling 2026-07-28, matching Pydantic v2 as probed on
2.13.4): deep-copy the recognized copyable shapes — mutable builtin
containers (deeply, opaque elements included), symbolic values (via
their own copy protocol; topology.MaybePartial is the marker),
dataclass instances, and types that opt in via
topology.CopyIfDefault — and SHARE everything else by reference:
the arbitrary-type template instance is reused across constructs,
which also makes unpicklable defaults (locks, client handles) legal.
Incidental deepcopyability is NOT the gate — an arbitrary object
defining __deepcopy__ is still shared, exactly like Pydantic;
extending CopyIfDefault is the declared per-type intent, and
default_factory remains the per-field escape hatch.
memo threads an enclosing __deepcopy__'s memo into the copy arms
(ValueSpecBase.__deepcopy__ routes its _default through here so a
spec clone keeps the shared template shared). The SHARE arm is
memo-coherent: it consults the memo first (another slot of the same
deepcopy may already have placed this object) and registers the
shared template otherwise — so sibling slots referencing the same
object (an Enum's _values candidate that IS the default) alias to
ONE object on the clone, preserving intra-spec invariants like
default in values.
Source code in pygx/typing/_class_schema.py
create_field
¶
create_field(
field_or_def: Field | FieldDef,
auto_typing: bool = True,
accept_value_as_annotation: bool = True,
parent_module: ModuleType | None = None,
) -> Field
Creates Field from its equivalence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_or_def
|
Field | FieldDef
|
a |
required |
auto_typing
|
bool
|
If True, infer value spec from Python annotations. Otherwise,
|
True
|
accept_value_as_annotation
|
bool
|
If True, allow default values to be used as annotations when creating the value spec. |
True
|
parent_module
|
ModuleType | None
|
(Optional) parent module for defining this field, which will be used for forward reference lookup. |
None
|
Returns:
| Type | Description |
|---|---|
Field
|
A |
Source code in pygx/typing/_class_schema.py
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 | |
create_schema
¶
create_schema(
fields: dict[FieldKeyDef, FieldValueDef] | list[Field | FieldDef],
name: str | None = None,
base_schema_list: list[Schema] | None = None,
allow_nonconst_keys: bool = False,
metadata: dict[str, Any] | None = None,
description: str | None = None,
for_cls: type[Any] | None = None,
parent_module: ModuleType | None = None,
) -> Schema
Creates Schema from a list of Fields or equivalences.
Examples:
The following code examples are equivalent:
schema = pg.typing.create_schema({
'a': int,
'b': (int, 'field b'),
'c': (pg.typing.Str(regex='.*'), 'field c', dict(meta1=1))
})
schema = pg.typing.create_schema([
('a', int),
('b', int, 'field b'),
('c', pg.typing.Str(regex='.*'), 'field c', dict(meta1=1)),
])
schema = pg.typing.create_schema([
pg.typing.Field('a', pg.typing.Int()),
pg.typing.Field('b', pg.typing.Int(), 'field b'),
pg.typing.Field(
'c', pg.typing.Str(regex='.*'), 'field c', dict(meta1=1)),
])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
dict[FieldKeyDef, FieldValueDef] | list[Field | FieldDef]
|
A dict, a list of field or equivalent values. A Field equivalent
value is either a Field object or a tuple of 2 - 4 elements: |
required |
name
|
str | None
|
An optional name for the schema. |
None
|
base_schema_list
|
list[Schema] | None
|
A list of schema objects as bases. |
None
|
allow_nonconst_keys
|
bool
|
Whether to allow non const keys in schema. |
False
|
metadata
|
dict[str, Any] | None
|
Optional dict of user objects as schema-level metadata. |
None
|
description
|
str | None
|
Optional description of the schema. |
None
|
for_cls
|
type[Any] | None
|
(Optional) the class that this schema applies to. |
None
|
parent_module
|
ModuleType | None
|
(Optional) parent module for defining this schema, which will be used for forward reference lookup. |
None
|
Returns:
| Type | Description |
|---|---|
Schema
|
Schema object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input type is incorrect. |
Source code in pygx/typing/_class_schema.py
2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 | |
docstr
¶
docstr(symbol: Any) -> DocStr | None
Gets the structured docstring of a Python symbol, or None if absent.
callable_eq
¶
Returns True if two (maybe) callables are equal.
For functions, x and y are considered equal when they are the same
instance or have the same code (e.g. two identical lambda x: x).
For methods, x and y are considered equal when:
- Static method: the same method from the same class hierarchy, e.g. a subclass inheriting a base class' static method.
- Class method: the same method from the same class. An inherited class method is considered a different class method.
- Instance method: when
selfis not bound, the same method from the same class hierarchy (like static methods); whenselfis bound, the same method on the same object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
An optional function or method object. |
required |
y
|
Any
|
An optional function or method object. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if |
bool
|
or derived from the same code with the same effect. |
Source code in pygx/typing/_inspection.py
get_outer_class
¶
get_outer_class(
cls: type[Any],
base_cls: type[Any] | tuple[type[Any], ...] | None = None,
immediate: bool = False,
) -> type[Any] | None
Returns the class enclosing cls in its nesting hierarchy.
Resolution follows cls.__qualname__ through the module's globals,
walking the nesting chain from the innermost enclosing class outwards.
Example:
class A1:
class B:
class C:
...
assert pg.typing.get_outer_class(A1.B) is A1
assert pg.typing.get_outer_class(A1.B.C) is A1.B
# With `base_cls`, the walk returns the innermost enclosing class
# that subclasses it (A1.B is not an A1 subclass; A1 subclasses
# itself).
assert pg.typing.get_outer_class(A1.B.C, base_cls=A1) is A1
assert pg.typing.get_outer_class(A1.B.C, base_cls=int) is None
assert pg.typing.get_outer_class(A1) is None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[Any]
|
The class to get the outer class for. |
required |
base_cls
|
type[Any] | tuple[type[Any], ...] | None
|
The base class the returned outer class must subclass. If
provided, enclosing classes that are not |
None
|
immediate
|
bool
|
Whether to consider only the immediate outer class, which
is returned as None if it is not a subclass of |
False
|
Returns:
| Type | Description |
|---|---|
type[Any] | None
|
The outer class of |
type[Any] | None
|
class satisfies |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in pygx/typing/_inspection.py
get_type
¶
Gets the type of a maybe generic type.
Source code in pygx/typing/_inspection.py
get_type_args
¶
Gets generic type args conditioned on an optional base class.
With base, resolves the args maybe_generic provides for that
generic base through the WHOLE inheritance chain, substituting TypeVars
hop by hop (#592) — class P(A[int]); class Q(P, Generic[Y]) resolves
(int,) for A, and class W(B[X], Generic[X]); W[str] resolves
(str,) for B. Returns () when the chain never binds the
base's params (the gradual-arm signal in is_subclass, #590); an
unbound TypeVar surviving substitution stays in the result (the arg
loop erases it).
Source code in pygx/typing/_inspection.py
has_generic_bases
¶
is_generic
¶
is_instance
¶
An isinstance extension that supports Any and generic types.
Equivalent to is_subclass(type(value), target) — see is_subclass
for the compatibility rules.
Source code in pygx/typing/_inspection.py
is_subclass
¶
An issubclass extension that supports Any and generic types.
typing.Any as the target accepts every source. A subscripted
generic target checks type args recursively, resolving the args the
source binds for the target's generic base through its inheritance
chain; unbound type parameters erase to Any (gradual semantics).
target may also be a tuple of types, matching any member.
Example:
import typing
assert pg.typing.is_subclass(bool, int)
assert pg.typing.is_subclass(int, typing.Any)
assert pg.typing.is_subclass(list[int], typing.Sequence[int])
assert pg.typing.is_subclass(list, list[int]) # Unbound args ~ Any.
assert not pg.typing.is_subclass(list[str], list[int])
Source code in pygx/typing/_inspection.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
substitute_type_params
¶
Substitutes type parameters in hint from env.
Top-level type variables directly, nested ones (list[T]) through
alias re-subscription. Parameters absent from env erase to Any
(gradual semantics, as is_subclass #590).
Source code in pygx/typing/_inspection.py
ensure_value_spec
¶
ensure_value_spec(
value_spec: ValueSpec, src_spec: ValueSpec, root_path: KeyPath | None = None
) -> ValueSpec | None
Extracts the part of value_spec that matches src_spec.
For a Union destination, the candidate compatible with src_spec
is selected; an Any destination imposes no constraint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value_spec
|
ValueSpec
|
The destination value spec to match against (possibly a
|
required |
src_spec
|
ValueSpec
|
The source value spec whose values should be acceptable to the destination. |
required |
root_path
|
KeyPath | None
|
An optional path for the value to include in error message. |
None
|
Returns:
| Type | Description |
|---|---|
ValueSpec | None
|
The matching (candidate) spec of |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
Source code in pygx/typing/_value_specs.py
enable_preset_args
¶
enable_preset_args(
include_all_preset_kwargs: bool = False, preset_name: str = "global"
) -> Callable[[Callable[..., Any]], Callable[..., Any]]
Decorator factory for functions that may use preset argument values.
Arguments whose defaults are PresetArgValue markers pick up their
values from the enclosing preset_args context at call time. Note the
decorator must be called (@enable_preset_args(), with parentheses).
Example:
@pg.typing.enable_preset_args()
def foo(x, y=pg.typing.PresetArgValue(default=1)):
return x + y
with pg.typing.preset_args(dict(y=2)):
print(foo(x=1)) # 3: y=2
print(foo(x=1)) # 2: y=1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_all_preset_kwargs
|
bool
|
Whether to also pass preset kwargs that
are not marked as |
False
|
preset_name
|
str
|
The name of the preset to read kwargs from. |
'global'
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., Any]], Callable[..., Any]]
|
A decorator that returns a function consuming preset argument values. |
Callable[[Callable[..., Any]], Callable[..., Any]]
|
A function without |
Source code in pygx/typing/_callable_ext.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
preset_args
¶
preset_args(
kwargs: dict[str, Any],
*,
preset_name: str = "global",
inherit_preset: str | bool = False
) -> Iterator[_ArgPresets]
Context manager providing preset kwargs to preset-enabled functions.
Within the context, functions decorated with enable_preset_args
resolve their PresetArgValue-defaulted arguments from kwargs.
See PresetArgValue for a usage example.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
dict[str, Any]
|
A dict of preset kwargs to be used by preset-enabled functions within the context. |
required |
preset_name
|
str
|
The name of the preset to hold the kwargs.
|
'global'
|
inherit_preset
|
str | bool
|
The name of the preset defined by the parent context to inherit kwargs from. Or a boolean to indicate whether to inherit a parent preset of the same name. |
False
|
Yields:
| Type | Description |
|---|---|
_ArgPresets
|
The current presets (an internal collection holding the preset |
_ArgPresets
|
kwargs by preset name). |
Source code in pygx/typing/_callable_ext.py
to_json_schema
¶
to_json_schema(
value: ValueSpec | Schema | Any,
*,
include_type_name: bool = True,
include_subclasses: bool = False,
inline_nested_refs: bool = False
) -> dict[str, Any]
Converts a schema, value spec or type annotation to JSON schema.
Example:
class A(pg.Object):
x: int = 1
assert pg.typing.to_json_schema(A, include_type_name=False) == {
'type': 'object',
'title': 'A',
'properties': {'x': {'type': 'integer', 'default': 1}},
'additionalProperties': False,
}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
ValueSpec | Schema | Any
|
A |
required |
include_type_name
|
bool
|
Whether class schemas include a |
True
|
include_subclasses
|
bool
|
Whether an object spec emits an |
False
|
inline_nested_refs
|
bool
|
Whether, when a single-referenced definition is
inlined, single-referenced definitions nested inside it are
inlined too. Definitions referenced more than once always stay
under |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A JSON schema dict. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
An enum spec holds a candidate that has no JSON representation. |
Source code in pygx/typing/_json_schema.py
options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2