ragraph.generic
#
Generic purpose classes and methods such as metadata models.
Metadata includes the kinds, labels, weights and annotations that we assign to our data objects. Standardizing this enables a more predictable experience.
Module Contents#
Classes#
A dictionary like object that with property-based access fields. |
|
Miscellaneous properties mapping such as tool-specific metadata. |
|
Numerical lower or upper bound for a value. Use with comparison operators. |
|
Numerical domain for a value. Use with "in" operator. |
|
Metadata for graph elements. |
|
Metadata filtering options. |
|
Seen values in an iterable of Metadata instances. |
Functions#
|
A |
- exception ragraph.generic.MappingValidationError#
Bases:
Exception
Common base class for all non-exit exceptions.
- ragraph.generic.field(fget: Callable)#
A
Mapping
field is a property that utilizes theMapping
’s data.Use it like the
@property
decorator and leave the function body blank (or pass):By inspecting the wrapped method’s name we derive the property’s key.
Getting data from the mapping is done by retrieving the key from the set values. If that key is not found, an attempt is made on the defaults. An error is thrown when the key is neither to be found in the data or defaults.
Setting data checks for nested
Mapping
keys to update those and otherwise defaults to simply storing the value. Updating a nestedMapping
field only updates the keys that are provided.Deleting data pops the key from the set values, but does not remove any defaults.
- class ragraph.generic.Mapping(*args, **kwargs)#
A dictionary like object that with property-based access fields.
It’s possible to include allowed keys, default values, and optional validators for certain keys/properties of a derived class.
>>> from ragraph.generic import Mapping, field >>> def check_int(value): ... assert value == 1 ... >>> class MyMap(Mapping): ... _protected = True ... _defaults = dict(myfield=1) ... _validators = dict(myfield=check_int) ... @field ... def myfield(self) -> int: ... '''My field's docstring''' ... >>> m = MyMap(myfield=3) >>> assert m.myfield == 3, "This should return our set value." >>> assert m.myfield == m['myfield'], "A mapping works like a dictionary." >>> del(m.myfield) # This deletes our override. >>> m.validate() # Checks whether myfield == 1.
- _protected = False#
Setting public properties is restricted to those in
self.keys
.
- _defaults :Dict[str, Any]#
Default values for included keys.
- _keys :Optional[Set[str]]#
Set of always allowed keys to set.
- _validators :Dict[str, Callable]#
Validators for included keys. Used when calling
self.validate
. Also seeself._post_validation
.
- __str__() str #
Return str(self).
- __repr__() str #
Return repr(self).
- __eq__(other: Any) bool #
Return self==value.
- __getitem__(key: str) Any #
Get an attribute via a dictionary accessor: self[‘key’].
- get(key: str, fallback: Any = None) Any #
Get an attribute with a fallback value if it isn’t found.
- __setattr__(key: str, value: Any) None #
Set an attribute : self.key = value.
Private properties are left untouched, public properties need permission. See
self._check_allowed
.
- __setitem__(key: str, value: Any) None #
Set an attribute via a dictionary accessor: self[‘key’] = value.
Private properties are left untouched, public properties need permission. See
self._check_allowed
.
- update(*args, **kwargs) None #
Update multiple keys at once.
- Parameters:
args – Dictionaries of key value pairs to update the set data with.
kwargs – Keyword arguments to update the set data with.
- __iter__()#
Provide an iterator.
- _is_mapping(key) bool #
Check whether this key is a mapping.
- items()#
Get defaults and overrides as a (key, value) dict_items iterator.
- keys() Set[str] #
The keys in this mapping. (defaults and overrides).
- validate() None #
Check whether the current data passes validation.
- _post_validation() None #
Validation to run at the end of regular validation. Does nothing by default.
Useful when a derived class needs to cross-validate certain keys instead of just a dedicated method per key.
- as_dict() Dict[str, Any] #
Return a copy as a dictionary with all submappings as dictionaries, too.
- class ragraph.generic.Annotations(*args, **kwargs)#
Bases:
Mapping
Miscellaneous properties mapping such as tool-specific metadata.
- _protected = False#
- class ragraph.generic.Bound(value: Union[int, float], inclusive: bool = True, report: Optional[str] = None)#
Numerical lower or upper bound for a value. Use with comparison operators.
- Parameters:
value – Numerical bound value.
inclusive – Whether the bound is inclusive.
report – Whether to report an “error”, “warn” or nothing (
None
) on bound violations.
- __str__() str #
Return str(self).
- __lt__(other: Union[int, float]) bool #
Used as a lower bound.
- __gt__(other: Union[int, float]) bool #
Used as an upper bound.
- _report(msg: str) None #
Report an error or warning depending on if the bound is set to ‘hard’.
- as_dict() Dict[str, Any] #
Serializable dictionary representation.
- class ragraph.generic.ContinuousDomain(lower: Optional[Bound] = None, upper: Optional[Bound] = None)#
Numerical domain for a value. Use with “in” operator.
- __str__() str #
Return str(self).
- __repr__() str #
Return repr(self).
- __contains__(value: Union[int, float]) bool #
Whether this continuous domain contains a value.
- as_dict() Dict[str, Any] #
Serializable dictionary representation.
- class ragraph.generic.Metadata(name: Optional[str] = None, kind: Optional[str] = None, labels: Optional[List[str]] = None, weights: Optional[Dict[str, Union[int, float]]] = None, annotations: Optional[Union[Annotations, Dict[str, Any]]] = None, uuid: Optional[Union[str, uuid.UUID]] = None)#
Metadata for graph elements.
- Parameters:
name – Instance name. Set to a copy of the UUID if
None
provided.kind – Kind or main category of this instance.
labels – Labels categorizing this instance.
weights – Dictionary of weights attached to this instance.
annotations – Miscellaneous properties of this instance.
uuid – UUID of this instance, generated when
None
provided.
- property uuid: uuid.UUID#
Instance UUID.
- property name: str#
Instance name. Given a UUID if None was provided.
- property kind: str#
Kind or main category of this instance.
- property labels: List[str]#
Labels categorizing this instance.
- property weights: Dict[str, Union[int, float]]#
Dictionary of weights attached to this instance.
- property weight: Union[int, float]#
Cumulative weight of this instance (read-only).
Returns the sum of
self.weights
.
- property annotations: Annotations#
Annotations of this instance.
Defaults to an empty
Annotations
instance.
- __copy__()#
- __deepcopy__(memo)#
- class ragraph.generic.MetadataFilter(uuids: Optional[Union[Iterable[str], Iterable[uuid.UUID]]] = None, names: Optional[Iterable[str]] = None, kinds: Optional[Iterable[str]] = None, labels: Optional[Iterable[str]] = None, weights: Optional[Iterable[str]] = None, weight_domains: Optional[Dict[str, ContinuousDomain]] = None, annotations: Optional[Iterable[str]] = None)#
Metadata filtering options.
- Parameters:
uuids – Filter by UUIDs.
names – Filter by names.
kinds – Filter by kinds.
labels – Filter by labels. Items should match at least one.
weights – Filter by weight labels. Items should match at least one.
weight_domains – Filter items by weight domains. (upper/lower bound)
annotations – Filter by annotation keys. Items should match at least one.
- _filters = ['uuids', 'names', 'kinds', 'labels', 'weights', 'weight_domains', 'annotations']#
- class ragraph.generic.MetadataOptions(objects: Iterable[Metadata], skip_uuids: bool = False, skip_names: bool = False)#
Seen values in an iterable of Metadata instances.
- Parameters:
objects – Objects derivated of the Metadata class.
skip_names – Whether to skip the names field.
- as_dict() Dict[str, Any] #
Serializable dictionary representation.