Predicate: A General, Highly-serializable Data Structure#
- class my.types.Predicate.Predicate(*, data: dict[str, list[str]] = {}, duplicates: bool = False, overwrite: bool = False)#
A Pydantic model wrapping
dict[str, list[str]]for string-based “vibe-typing” usage.It accepts input from various sources: dictionaries, Pydantic models, JSON-ish dictionary strings, iterables of key-value pairs, or other Predicates. The constructor normalizes all inputs to the canonical dictionary-of-lists format, optionally deduplicating values.
Serialization supports nested dictionary structures using dot notation in keys. A field like
"user.name"becomes{"user": {"name": value}}in the output. This makes Predicate suitable for representing structured data that originates as flat key-value pairs but needs hierarchical output. Pydantic serialization andrepr()abbreviate single-element lists but preserve every stored string verbatim, so values such as'y','0', and date-shaped text never change type.to_yaml()additionally infers familiar YAML scalar types for human-readable output.Examples
Build a predicate and inspect its fields:
>>> from my import Predicate >>> pred = Predicate.new({'tags': ['py', 'docs'], 'user.name': 'robb'}) >>> pred {'tags': ['py', 'docs'], 'user.name': 'robb'} >>> pred['tags'] ['py', 'docs'] >>> 'tags' in pred True >>> pred.size 3
Combine predicates with set-like operators:
>>> pred = Predicate.new({'a': ['x1', 'x2'], 'b': 'x3'}) >>> pred + {'c': 'x4'} {'a': ['x1', 'x2'], 'b': 'x3', 'c': 'x4'} >>> pred - {'a': ['x1']} {'a': 'x2', 'b': 'x3'} >>> pred & ['a'] {'a': ['x1', 'x2']}
I Initial Methods#
- classmethod Predicate.new(*args: list | tuple | Set | deque | array | range | Mapping[Hashable, Any] | Iterable[tuple[Hashable, Any]] | ItemsView | BaseModel | object | str | bytes | bytearray | memoryview | IO | int | float | complex | bool | date | time | datetime | timedelta | Enum | Self | None, duplicates: bool = False, overwrite: bool = False, **kwargs) Self#
Construct a new Predicate instance, flexibly coercing most mapping-like objects.
- Parameters:
*args – Mapping-like sources to merge: dicts, Pydantic models, JSON-ish dictionary strings, iterables of key-value pairs, and/or other Predicates.
duplicates – Whether to allow duplicate values within a field’s list.
overwrite – The default overwriting behavior for later
write()calls.**kwargs – Additional field-value pairs to merge, as keyword arguments.
- Returns:
A new Predicate with empty fields and values filtered out.
Examples
Coerce several source shapes at once:
>>> from my import Predicate >>> Predicate.new({'lang': 'python'}) {'lang': 'python'} >>> Predicate.new([('lang', ['python', 'rust'])]) {'lang': ['python', 'rust']} >>> Predicate.new('{"lang": "python"}', level='expert') {'lang': 'python', 'level': 'expert'}
II Primary Methods#
- Predicate.to_yaml(**kwargs) str#
Serialize the Predicate to a YAML string, expanding dotted keys into nesting.
Examples
Serialize a predicate with a dotted key:
>>> from my import Predicate >>> pred = Predicate.new({'tags': ['py', 'docs'], 'user.name': 'robb'}) >>> print(pred.to_yaml(), end='') tags: - py - docs user: name: robb
- classmethod Predicate.from_yaml(text: str, **kwargs) Predicate#
Create a Predicate from a YAML string.
Examples
Round-trip a field through YAML:
>>> from my import Predicate >>> Predicate.from_yaml('lang:\n- python\n- rust\n') {'lang': ['python', 'rust']}
- Predicate.write(field: str, value: str | bytes | bytearray | memoryview | IO | int | float | complex | bool | date | time | datetime | timedelta | Enum | list | tuple | Set | deque | array | range | Mapping[Hashable, Any] | Iterable[tuple[Hashable, Any]] | ItemsView | BaseModel | object, overwrite: bool | None = None)#
Add a value to a field in this predicate, with custom overriding logic.
- Parameters:
field – The field to write to.
value – The value to write.
overwrite – Whether to overwrite existing values. If
None, uses the instance’soverwritesetting.
Examples
Append to a field, then overwrite it:
>>> from my import Predicate >>> pred = Predicate.new({'k': 'a'}) >>> pred.write('k', 'b') >>> pred {'k': ['a', 'b']} >>> pred.write('k', 'c', overwrite=True) >>> pred {'k': 'c'}
III Properties#
IV Accessors#
- Predicate.get(field: str, default: list[str] | None = None) list[str]#
Get the values associated with a field, or a default if the field is not present.
- Predicate.pop(field: str, default: list[str] | None = None) list[str]#
Remove and return a field’s values, or a default if it doesn’t exist.
V Mutators#
- Predicate.add_to_set(field: str, value: Any) None#
Add a value to the set of values for a given field, creating it if necessary.
- Parameters:
field – The field to add the value to.
value – The value to add, which will be cast to a string and added if not present.
Examples
Add values, ignoring duplicates:
>>> from my import Predicate >>> pred = Predicate.new({'s': ['a']}) >>> pred.add_to_set('s', 'b') >>> pred.add_to_set('s', 'a') >>> pred {'s': ['a', 'b']}