pygx.typing¶
Symbolic typing.
typing
¶
Symbolic typing.
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
Runtime typing_ for more details. -
Allow symbolic attributes to be placeheld by special symbols, in order to represent abstract concepts such as a space of objects. E.g. hyper primitives like
pygx.oneofplaceholds a symbolic attribute to create a space of values for that attribute. SeeSymbolic placeholding_ 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
difficut 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::
(key specification, value specification, doc string, field metadata)
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::
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=0.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=[])),
('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, default=[])),
# 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([
('p1', pg.typing.Int()),
('p2', 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()],
kwargs=[('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))
])
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::
class A(pg.Object): x: 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: pg.typing.Int(max_value=5, default=2) z: pg.typing.Str('foo').freeze()
assert 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.
Symbolic placeholding
Symbolic placeholding enables scenarios that requires an abstract (non-material) representation of objects - for example - a search space or a partially bound object. Such objects with placeheld 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 = f(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 manipulated it: f.sym_rebind(x=1, y=2)
# Returns 3 f()
Symbolic placeholding is achieved by the pygx.CustomTyping
interface, which was intended as a mechanism to extend the typing system
horizontally without modifying the pygx.ValueSpec of existing
classes' attributes.
This is done by allowing the CustomTyping subclasses to take over value
validation and transformation from an attribute's original ValueSpec
via pygx.CustomTyping.custom_apply method.
Following is an example of using CustomTyping to extend the schema system::
class FloatTensor(pg.typing.CustomTyping):
def __init__(self, tensor):
self._tensor = tensor
def custom_apply(
self, path, value_spec, allow_partial, child_transform):
if isinstane(value_spec, pg.typing.Float):
# Validate initial tensor, we can also add an TF operator to guard
# tensor value to go beyond value_spec.min_value and max_value.
value_spec.apply(self._tensor.numpy())
# Shortcircuit .apply and returns object itself as final value.
return (False, self)
else:
raise ValueError('FloatTensor can only be applied to float type.')
class Foo(pg.Object): x: float
# FloatTensor can be accepted for all symbolic attributes # with Float value spec. f = Foo(x=FloatTensor(tf.constant(1.0)))
MissingValue
¶
Argument
dataclass
¶
Definition for a callable argument.
Kind
¶
Bases: Enum
Arugment 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
PY3 function signature.
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 (PY3). |
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
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
735 736 737 738 739 740 741 742 743 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 | |
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
821 822 823 824 825 826 827 828 829 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 | |
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,
enable_wrap: bool | 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::
(key specification, value specification, doc string, field metadata)
For example::
(pg.typing.StrKey('foo.*'), pg.typing.Int(), 'Attributes with foo', {'user_data': 'bar'})
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 if 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
|
enable_wrap
|
bool | None
|
Whether raw |
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
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 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 | |
metadata
property
¶
Metadata of this field.
Metadata is defined as a dict type, so we can add multiple annotations to a field.
userdata = field.metadata.get('userdata', None):
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).
enable_wrap
property
¶
Whether raw dict / list are wrapped into pg.Dict / pg.List.
Gates only the symbolic transform callback inside
Field.apply — type-validation and __pg_accept__
coercions are unaffected. None resolves to enable_init
(init → True, non-init → False) at this layer, so non-init
fields skip wrapping even when enable_validation is
manually re-enabled. (pg.Object's sym=False materializes
an explicit False onto init fields, overriding this default.)
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
Apply current field to a value, which validate and complete the value.
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
|
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
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 an 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(value_spec=pg.Dict([
('x', pg.typing.Float(min_value=0.0)),
(pg.typing.StrKey('foo.*'), pg.typing.Int())
]))
You may noticed that the code above pass a string 'x' for 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 either use 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
|
An |
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: 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: pg.typing.Int(max_value=5, default=2) z: pg.typing.Str('foo').freeze()
assert 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. If required a field is missing from the schema, and the
object's allow_partial is set to False, a KeyError will raise. Otherwise
a partially validated/transformed dict will be returned. Missing values in the
object will be placeheld by :const:pygx.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
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 | |
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 appeared onces will be used in the merged schema.
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
|
(Optinoal) 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 that is acceptable to the other schema is acceptable to 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
|
string as input key. |
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_enable_wrap: bool = False,
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: The value with | | applicable Field is | Not None | Not MISSING_VALUE found in schema. | | value. | | The value is | | not present for a | Not None | MISSING_VALUE key defined in schema. | | 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_enable_wrap
|
bool
|
When True, |
False
|
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
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 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 | |
validate
¶
validate(
dict_obj: dict[str, Any],
allow_partial: bool = False,
root_path: KeyPath | None = None,
) -> None
Validates whether dict object is conformed with 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 | .apply |
| validation and | |
| transformation | |
+-----------------------+-------------------------------------------------+
| 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::
pg.typing.<ValueSpecClass>(
[validation-rules],
[default=<default>],
[transform=<transform>])
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::
pg.typing.Int().noneable().set_default(1)
Usage
To apply a value specification on an user input to get the accepted value,
pygx.ValueSpec.apply shall be used::
value == pg.typing.Int(min_value=1).apply(4)
assert value == 4
Extension
Besides, a ValueSpec object can extend another ValueSpec object to
obtain a more restricted ValueSpec object. For example::
pg.typing.Int(min_value=1).extend(pg.typing.Int(max_value=5))
will end up with::
pg.typing.Int(min_value=1, max_value=5)
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::
pg.typing.Int().freeze(1)
ValueSpec objects can be created and modified with chaining. For example::
pg.typing.Int().noneable().set_default(1)
The code above creates an int specification with default value 1 and can accept None.
ValueSpec object can also be derived from annotations. For example, the
class below uses explicit value specs::
class A(pg.Object): a: pg.typing.List(pg.typing.Str()) b: pg.typing.Dict().set_default({'key': 'value'}) c: pg.typing.List(pg.typing.Any()).noneable() x: pg.typing.Int() y: pg.typing.Str().noneable() z: pg.typing.Union([pg.typing.Int(), pg.typing.Float()])
which can equivalently be written using 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
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 NO_FAST_APPLY (or any
FastApplyInfo() with is_eligible=False).
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 referenes 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 post-validation user transform callable and returns self.
materialize_default
abstractmethod
¶
Returns a per-instance default value.
If a default_factory is set, calls it and validates the result.
Otherwise returns a deep copy of the static default. 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 symoblic attribute and want 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). Choose the default value if the input value is MISSING_VALUE
(2). Check whether the input value is None.
(2.a) Input value is None and value_spec.is_noneable() is False,
raises Error.
(2.b) Input value is not None or value_spec.is_noneable() is True,
goto step (3).
(3). Run value_spec.custom_apply if the input value is a
CustomTyping instance.
(3.a). If value_spec.custom_apply returns a value that indicates to
proceed with standard apply, goto step (4).
(3.b). Else goto step (6)
(4). Check the input value type against the value_spec.value_type.
(4.a). If their value type matches, go to step (5)
(4.b). Else if the value spec's value type accepts the input via a
__pg_accept__(value) classmethod, perform the coercion
and go to step (5).
(4.c) Otherwise raises type mismatch.
(5). Perform type-specific and user validation and transformation.
For complex types such as Dict, List, Tuple, call child_spec.apply
recursively on the child fields.
(6). Perform user transform and returns final value
(invoked at Field.apply.)
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
|
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 of custom value type.
Instances of subclasses of CustomTyping can be assigned to fields of
any ValueSpec, and take over apply via custom_apply method.
As a result, CustomTyping makes the schema system extensible without modifying existing value specs. For example, value generators can extend CustomTyping and be assignable to any fields.
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,
)
Docstring.
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::
key = pg.typing.ConstStrKey('x')
assert key == 'x'
assert hash(key) == hash('x')
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.
Example::
# Create a key spec that specifies list items from 1 to 5 (zero-based).
key = pg.typing.ListKey(min_value=1, max_value=5)
assert key.match(1)
assert key.match(5)
assert not key.match(0)
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_value
|
int
|
Min value that is acceptable for the list index. |
0
|
max_value
|
int | None
|
Max value that is acceptable for the list index. If None, there is no upper bound for list index. |
None
|
Source code in pygx/typing/_key_specs.py
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.
format
¶
Format this object.
Source code in pygx/typing/_key_specs.py
NonConstKey
¶
StrKey
¶
Bases: NonConstKey
Class that represents a variable string key.
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.
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.
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 required 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 is not accceptable. |
False
|
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.
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 is not accceptable. |
False
|
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.
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()
# An 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.
Source code in pygx/typing/_value_specs.py
3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 | |
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]
| 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,
)
Bases: Generic, ValueSpecBase
Value spec for dict type.
Examples::
# A required symbolic 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] | 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 value
spec.
If None, it specifies a schema-less Dict that may accept arbitrary
key/value pairs.
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 is not accceptable. |
False
|
Source code in pygx/typing/_value_specs.py
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 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 | |
noneable
¶
Override noneable in Dict to always set default value None.
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.
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')
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 is not accceptable. |
False
|
Source code in pygx/typing/_value_specs.py
noneable
¶
Noneable is specially treated for Enum.
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.
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 is not accceptable. |
False
|
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.
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.
Source code in pygx/typing/_value_specs.py
Generic
¶
Generic value spec.
GenericMeta
¶
Bases: ABCMeta
Metaclass for generic value spec.
GenericTypeAlias
¶
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::
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.
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 is not accceptable. |
False
|
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
)
Bases: Generic, ValueSpecBase
Value spec for list type.
Examples::
# A required non-negative integer list. pg.typing.List(pg.typing.Int(min_value=0))
# A optional str list with 2-5 items. pg.typing.List(pg.typing.Str(), min_size=2, max_size=5).noneable()
# An 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 is not accceptable. |
False
|
min_length
|
int | None
|
Synonym of |
None
|
max_length
|
int | None
|
Synonym of |
None
|
Source code in pygx/typing/_value_specs.py
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 | |
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 value of acceptable values. |
None
|
max_value
|
int | 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 is not accceptable. |
False
|
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.
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 is not accceptable. |
False
|
Source code in pygx/typing/_value_specs.py
format
¶
Format this object.
Source code in pygx/typing/_value_specs.py
Optional
¶
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 is not accceptable. |
False
|
Source code in pygx/typing/_value_specs.py
Sequence
¶
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.
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. |
None
|
is_noneable
|
bool
|
If True, None is acceptable. |
False
|
frozen
|
bool
|
If True, values other than the default value is not accceptable. |
False
|
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.
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)])
# A 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 list. Applicable only for variable-length tuple. |
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], 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 is not accceptable. |
False
|
min_length
|
int | None
|
Synonym of |
None
|
max_length
|
int | None
|
Synonym of |
None
|
Source code in pygx/typing/_value_specs.py
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 | |
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.
Examples::
# A required type or subclass of A. pg.typing.Type(A)
# An 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)
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.
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})
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 is not accceptable. |
False
|
Source code in pygx/typing/_value_specs.py
3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 | |
forward_refs
¶
forward_refs() -> set[ForwardRef]
Returns forward references used in this spec.
Source code in pygx/typing/_value_specs.py
noneable
¶
Customized noneable for Union.
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
¶
Helper class for invoking callable objects with optional keyword args.
Examples::
f = pg.typing.CallableWithOptionalKeywordArgs(lambda x: x ** 2, 'y') # Returns 4. Keyword 'y' is ignored. f(2, y=3)
Source code in pygx/typing/_callable_ext.py
PresetArgValue
¶
Bases: Formattable
Value placeholder for arguments whose value will be provided by presets.
Example:
def foo(x, y=pg.PresetArgValue(default=1)) return x + y
with pg.preset_args(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 annotations from str.
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. |
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
44 45 46 47 48 49 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 | |
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
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 661 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 | |
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 description form docstrs. |
True
|
remove_self
|
bool
|
If True, remove the first |
True
|
include_return
|
bool
|
If True, include the return value spec in the schema with key 'return_value'. |
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 signature from a python callable.
Source code in pygx/typing/_callable_signature.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
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 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 | |
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
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 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 | |
callable_eq
¶
Returns True if two (maybe) callables are equal.
x and y are considered equal when they are the same
instance or have the same code (e.g. lambda x: x).
x and y are considered equal when:
static method: The same method from the same class hierarchy. E.g. subclass
inherits a base class' static method.
class method: The same method from the same class. Inherited class method
are considered different class method.
instance method: When self is not bound, the same method from the same
class hierarchy (like static method). When self is 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 optinoal function or method object. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Returns True if |
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 outer class.
Example::
class A: pass
class A1: class B: class C: ...
pg.typing.outer_class(B) is A1 pg.typing.outer_class(C) is B pg.typing.outer_class(C, base_cls=A) is None pg.typing.outer_class(C, base_cls=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 of the outer class. If provided, an outer class
that is not a subclass of |
None
|
immediate
|
bool
|
Whether to return the immediate outer class or a class in the
nesting hierarchy that is a subclass of |
False
|
Returns:
| Type | Description |
|---|---|
type[Any] | None
|
The outer class of |
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.
Source code in pygx/typing/_inspection.py
has_generic_bases
¶
is_generic
¶
is_instance
¶
is_subclass
¶
An issubclass extension that supports Any and generic types.
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
Extract counter part from value spec that matches dest spec type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value_spec
|
ValueSpec
|
Value spec. |
required |
src_spec
|
ValueSpec
|
Destination value spec. |
required |
root_path
|
KeyPath | None
|
An optional path for the value to include in error message. |
None
|
Returns:
| Type | Description |
|---|---|
ValueSpec | None
|
value_spec of src_spec_type |
Raises:
| Type | Description |
|---|---|
TypeError
|
When value_spec cannot match src_spec_type. |
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 for functions that maybe use preset argument values.
Usage::
@pg.typing.enable_preset_args def foo(x, y=pg.typing.PresetArgValue(default=1)): return x + y
with pg.typing.preset_args(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 include all preset kwargs (even
not makred as |
False
|
preset_name
|
str
|
The name of the preset to specify kwargs. |
'global'
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., Any]], Callable[..., Any]]
|
A decorated function that could consume the preset argument values. |
Source code in pygx/typing/_callable_ext.py
preset_args
¶
preset_args(
kwargs: dict[str, Any],
*,
preset_name: str = "global",
inherit_preset: str | bool = False
) -> Iterator[dict[str, Any]]
Context manager to enable calling with user kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
dict[str, Any]
|
The preset kwargs to be used by preset-enabled functions within the context. |
required |
preset_name
|
str
|
The name of the preset to specify 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 |
|---|---|
dict[str, Any]
|
Current preset kwargs. |
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 value spec to JSON schema.
Source code in pygx/typing/_json_schema.py
options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2