Announcement

class domprob.sensors.dec._Sensor(instrum, required=False)[source]

Bases: Generic[_MethodCls, _Instrum, _P, _R]

Decorator class for associating metadata and validating methods.

This class enables the decoration of methods with metadata describing their required instruments. It enforces runtime validate to ensure that the method is called with the correct parameters and that the instrument argument satisfies the specified requirements.

The @sensors decorator can be stacked.

Warning

It is strongly recommended that instrument classes defined in stacked decorators inherit from the same base class or implement the same typing protocol.

Parameters:
  • instrum (type[_Instrum]) – The instrument class required by the decorated method.

  • required (bool) – Whether the instrument is required. Defaults to False.

Examples

Simple implementation:

>>> class PrintInstrument:
...
...     @staticmethod
...     def stdout(msg: str) -> None:
...         print(msg)
...
...     def __repr__(self) -> str:
...         return f"{self.__class__.__name__}()"
...
>>> # Define a class with a decorated method
>>> from domprob import sensor
>>>
>>> class Foo:
...     @sensor(PrintInstrument)
...     def bar(self, instrument: PrintInstrument) -> None:
...         instrument.stdout(f"Executing with {instrument!r}")
...
>>> foo = Foo()
>>> instru = PrintInstrument()
>>>
>>> foo.bar(instru)
Executing with PrintInstrument()

Supporting the same sensors implementation with multiple instruments:

>>> import logging
>>> from abc import ABC, abstractmethod
>>>
>>> # Define instruments
>>> class AbstractStdOutInstrument(ABC):
...     @abstractmethod
...     def stdout(self, cls_name: str) -> None:
...         raise NotImplementedError
...
...     def __repr__(self) -> str:
...         return f"{self.__class__.__name__}()"
...
>>> class PrintInstrument(AbstractStdOutInstrument):
...     def stdout(self, cls_name: str) -> None:
...         print(f"Observing '{cls_name}' with '{self!r}'")
...
>>> class LogInstrument(AbstractStdOutInstrument):
...
...     def __init__(self):
...         self.logger = logging.getLogger()
...         self.logger.setLevel(logging.INFO)
...
...     def stdout(self, cls_name: str) -> None:
...         logger = logging.getLogger()
...         logger.setLevel(logging.INFO)
...         logger.info(f"Observing '{cls_name}' with '{self!r}'")
...
>>> # Define a class with a decorated method
>>> from domprob import sensor
>>>
>>> class Foo:
...     @sensor(PrintInstrument)
...     @sensor(LogInstrument)
...     def bar(self, instrument: AbstractStdOutInstrument) -> None:
...         instrument.stdout(self.__class__.__name__)
...
>>> foo = Foo()
>>> instru = PrintInstrument()
>>>
>>> foo.bar(instru)
Observing 'Foo' with 'PrintInstrument()'
__call__(method)[source]

Wraps a method to associate metadata and enforce runtime validate.

This method is invoked when the @sensors decorator is used on a method. It attaches metadata, including the instrument class and requirement status, to the method and enforces validate when the method is called at runtime.

Parameters:

method (Callable[P, R]) – The method to decorate.

Returns:

A wrapped version of the input method with metadata and validate applied.

Return type:

Callable[P, R]

Examples

>>> class SomeInstrument:
...     pass
...
>>> # Define a class with a decorated method
>>> from domprob import sensor
>>>
>>> class Foo:
...     @sensor(SomeInstrument)
...     def bar(self, instrument: SomeInstrument) -> None:
...         print(f"Executing with {instrument!r}")
...
>>> foo = Foo()
>>> instru = SomeInstrument()
>>>
>>> foo.bar(instru)
Executing with <...SomeInstrument object at 0x...>
__repr__()[source]

Returns a string representation of the _Sensor instance.

This method provides a concise, informative string representation of the _Sensor instance, including its instrument class and requirement status.

Returns:

A string representation of the _Sensor instance.

Return type:

str

Examples

>>> class SomeInstrument:
...     pass
...
>>> sensor = _Sensor(SomeInstrument)
>>> repr(sensor)
"_Sensor(instrum=<class '...SomeInstrument'>)"
domprob.sensors.dec.sensor

alias of _Sensor

class domprob.sensors.instrums.Instruments(metadata)[source]

Bases: Generic[_InstruCls]

Manages and provides access to instrument classes for a decorated method’s metadata.

Parameters:

metadata (SensorMetadata) – The metadata object managing the associated method’s metadata.

Examples

>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> meta = meth_meta.SensorMetadata(Foo.bar)
>>>
>>> # Access metadata instruments
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments(meta)
>>>
>>> instruments
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
__eq__(other)[source]

Checks equality between the current Instruments instance and another object.

This method determines whether the provided object is an instance of Instruments and whether their associated metadata are equal. Two Instruments instances ar considered equal if they manage the same SensorMetadata.

Parameters:

other (Any) – The object to compare with the current Instruments instance.

Returns:

True if the provided object is an Instruments

instance and their metadata are equal.

Return type:

bool

Examples

>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create Instruments instances for the same method
>>> from domprob.sensors.instrums import Instruments
>>> instruments1 = Instruments.from_method(Foo.bar)
>>> instruments2 = Instruments.from_method(Foo.bar)
>>>
>>> instruments1 == instruments2
True
>>> # Create Instruments instance for a different method
>>> class Baz:
...     def qux(self):
...         pass
...
>>> instruments3 = Instruments.from_method(Baz.qux)
>>> instruments1 == instruments3
False
>>> # Compare with an unrelated object
>>> instruments1 == "Not an Instruments instance"
False
__iter__()[source]

Iterates over all instruments.

Yields:

_InstrumentTupleClsGen

Instrument classes associated with

the method’s metadata.

Return type:

Generator[tuple[TypeVar(_InstruCls, bound= type[Any]), bool], None, None]

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create instruments handler for method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>>
>>> # Define an instrument
>>> class SomeInstrument:
...     pass
...
>>> instruments.record(SomeInstrument, True)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> list(instruments)
[(<class 'domprob.sensors.instrums.SomeInstrument'>, True)]
__len__()[source]

Returns the number of instrument entries associated with the method’s metadata.

This method provides the total count of all instrument classes recorded in the metadata for the associated method.

Returns:

The total number of instrument classes recorded.

Return type:

int

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create instruments handler for method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>> # Initially, no instruments are recorded
>>> len(instruments)
0
>>> # Define an instrument
>>> class SomeInstrument:
...     pass
...
>>> # Record the instrument
>>> instruments.record(SomeInstrument, required=True)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> len(instruments)
1
__repr__()[source]

Returns a string representation of the Instruments instance.

Returns:

The string representation of the Instruments object.

Return type:

str

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create instruments handler for method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>> repr(instruments)
'Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))'
classmethod from_method(method)[source]

Creates an Instruments instance from a method.

Provides a convenient way to initialise an Instruments object directly from a method without explicitly creating an SensorMetadata instance.

Parameters:

method (Callable[…, Any]) – The method for which the instruments should be managed.

Returns:

An Instruments instance for managing the

method’s metadata.

Return type:

Instruments

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create an Instruments instance directly from the method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>> instruments
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
is_required(instrument_cls)[source]

Checks if any recorded instrument of the same instrument type given is required.

Parameters:

instrument_cls (TInstruCls) – The instrument type to check against the method’s metadata.

Returns:

True if any instrument of the given type is marked

as required, otherwise False.

Return type:

bool

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create instruments handler for method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>>
>>> # Define an instrument class
>>> class SomeInstrument:
...     pass
...
>>> instruments.is_required(SomeInstrument)
False
>>> instruments.record(SomeInstrument, False)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> instruments.record(SomeInstrument, True)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> instruments.is_required(SomeInstrument)
True
property non_req_instrums: Generator[_InstruCls, None, None]

Generator yielding supported instrument classes marked as not required in the method’s metadata.

Yields:

TInstrumentClsGen – Non-required instrument classes.

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create an Instruments instance directly from the method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>>
>>> # Define an instrument class
>>> class SomeInstrument:
...     pass
...
>>> # Add a required instrument
>>> instruments.record(SomeInstrument, required=True)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>>
>>> list(instruments.non_req_instrums)
[]
>>> instruments.record(SomeInstrument, required=False)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> list(instruments.non_req_instrums)
[<class '...SomeInstrument'>]
record(instrument, required)[source]

Adds an instrument entry to the method’s metadata.

Parameters:
  • instrument (type[BaseInstrument]) – The instrument class to add to the method’s metadata.

  • required (bool) – Whether the instrument is required.

Returns:

The updated Instruments instance.

Return type:

Instruments

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create instruments handler for the method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>>
>>> # Define an instrument class
>>> class SomeInstrument:
...     pass
...
>>> # Add a required instrument
>>> instruments.record(SomeInstrument, required=True)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> # Add a non-required instrument
>>> instruments.record(SomeInstrument, required=False)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
property req_instrums: Generator[_InstruCls, None, None]

Generator yielding supported instrument classes marked as required in the method’s metadata.

Yields:

TInstrumentClsGen – Required instrument classes.

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create an Instruments instance directly from the method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>>
>>> # Define an instrument class
>>> class SomeInstrument:
...     pass
...
>>> instruments.record(SomeInstrument, required=False)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> list(instruments.req_instrums)
[]
>>> instruments.record(SomeInstrument, required=True)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> list(instruments.req_instrums)
[<class '...SomeInstrument'>]
supported(required=None)[source]

Yields supported instrument classes filtered by requirement.

Parameters:

required (bool, optional) – If True, yields only required instruments. If False, yields only non-required instruments. If None, yields all instruments. Defaults to None.

Yields:

TInstrumentClsGen

Instrument classes that match the

filter criteria.

Return type:

Generator[TypeVar(_InstruCls, bound= type[Any]), None, None]

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create instruments handler for method
>>> from domprob.sensors.instrums import Instruments
>>> instruments = Instruments.from_method(Foo.bar)
>>>
>>> # Define an instrument class
>>> class SomeInstrument:
...     pass
...
>>> # Add instruments
>>> instruments.record(SomeInstrument, required=True)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>>
>>> # Filter instruments based on their requirement status
>>> list(instruments.supported(True))
[<class '...SomeInstrument'>]
>>> list(instruments.supported(False))
[]
>>> instruments.record(SomeInstrument, required=False)
Instruments(metadata=SensorMetadata(method=<function Foo.bar at 0x...>))
>>> list(instruments.supported())
[<class '...SomeInstrument'>, <class '...SomeInstrument'>]
class domprob.sensors.meth_meta.SensorMetadata(method)[source]

Bases: object

Stores and manages metadata for an instance method.

Parameters:

method (Callable[…, Any]) – The method for which the metadata is to be managed.

Examples

>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> meta = meth_meta.SensorMetadata(Foo.bar)
>>>
>>> meta
SensorMetadata(method=<function Foo.bar at 0x...>)
METADATA_ATTR: str = '__sensor_metadata__'
__eq__(other)[source]

Equality operator to check if two SensorMetadata instances are equivalent.

Parameters:

other (Any) – The object to compare with the current SensorMetadata instance. Typically expected to be another SensorMetadata object.

Returns:

Returns True if both operands reference the

metadata of the same instance method

Return type:

bool

Examples

>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> meta_1 = meth_meta.SensorMetadata(Foo.bar)
>>> meta_1 == "string"
False
>>> meta_2 = meth_meta.SensorMetadata(Foo.bar)
>>> meta_1 == meta_2
True
>>>
>>> # Define an instrument
>>> class SomeInstrument:
...     pass
...
>>> meta_1.add(SomeInstrument, True)
SensorMetadata(method=<function Foo.bar at 0x...>)
>>> meta_1 == meta_2  # Both reference the same method
True
__iter__()[source]

Iterates over all metadata entries recorded for the method.

Yields:

SensorMetadataEntry

Metadata items associated with the

method.

Return type:

Generator[SensorMetadataEntry, None, None]

Examples

>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> meta = meth_meta.SensorMetadata(Foo.bar)
>>>
>>> # Define an instrument
>>> class SomeInstrument:
...     pass
...
>>> # Add entries to the metadata
>>> meta.add(SomeInstrument, True).add(SomeInstrument, False)
SensorMetadata(method=<function Foo.bar at 0x...>)
>>>
>>> meta_iter = iter(meta)
>>> next(meta_iter)
SensorMetadataEntry(instrument_cls=<class '...SomeInstrument'>, required=True)
>>> next(meta_iter)
SensorMetadataEntry(instrument_cls=<class '...SomeInstrument'>, required=False)
__len__()[source]

Returns the number of metadata entries.

Returns:

The number of metadata entries recorded for the

method.

Return type:

int

Examples

>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> meta = meth_meta.SensorMetadata(Foo.bar)
>>>
>>> len(meta)
0
>>> # Define an instrument
>>> class SomeInstrument:
...     pass
...
>>> meta.add(SomeInstrument, required=True)
SensorMetadata(method=<function Foo.bar at 0x...>)
>>> len(meta)
1
__repr__()[source]

Returns a string representation of the metadata instance.

Returns:

The string representation.

Return type:

str

Examples

>>> # Define a class with a method to decorate
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> meta = meth_meta.SensorMetadata(Foo.bar)
>>> repr(meta)
'SensorMetadata(method=<function Foo.bar at 0x...>)'
add(instrument, required)[source]

Adds a sensors’ metadata entry to the method.

Parameters:
  • instrument (type[BaseInstrument]) – The instrument class to add to the method’s metadata.

  • required (bool) – Whether the instrument is required.

Returns:

The updated metadata instance.

Return type:

SensorMetadata

Examples

>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> meta = meth_meta.SensorMetadata(Foo.bar)
>>>
>>> len(meta)
0
>>> # Define an instrument
>>> class SomeInstrument:
...     pass
...
>>> meta.add(SomeInstrument, required=True)
SensorMetadata(method=<function Foo.bar at 0x...>)
>>> len(meta)
1
class domprob.sensors.meth_meta.SensorMetadataEntry(instrument_cls, required)[source]

Bases: object

Represents metadata entry for a sensors’ method. Includes the instrument class and its requirement status.

Parameters:
  • instrument_cls (type[BaseInstrument]) – The type of instrument for which the sensors should be executed.

  • required (bool) – Whether the instrument instance at runtime is required or optional for the sensors. Defaults to True if not provided during instantiation.

Examples

>>> class SomeInstrument:
...     pass
...
>>> # Define a class with a method
>>> class Foo:
...     def bar(self):
...         pass
...
>>> # Create metadata for the method
>>> from domprob.sensors import meth_meta
>>> entry = meth_meta.SensorMetadataEntry(SomeInstrument, required=False)
>>> entry
SensorMetadataEntry(instrument_cls=<class '...SomeInstrument'>, required=False)
>>> entry.instrument_cls
<class '...SomeInstrument'>
>>> entry.required
False
__eq__(other)

Return self==value.

__repr__()

Return repr(self).

instrument_cls: type[Any]
required: bool
class domprob.sensors.meth.SensorMethod(meth, *, static=False, supp_instrums=None)[source]

Bases: BaseSensorMethod, Generic[_PMeth, _RMeth]

Represents a decorated method with associated metadata.

This class acts as a wrapper and provides an interface to interact with the supported instruments of a method decorated with @sensors. It also facilitates partially binding runtime arguments to the method before method execution.

Parameters:

meth (Callable[P, R]) – The decorated method to be managed.

Examples

>>> class SomeInstrument:
...     pass
...
>>> # Define a class with a decorated method
>>> from domprob import sensor
>>>
>>> class Foo:
...     @sensor(SomeInstrument)
...     def bar(self, instrument: SomeInstrument) -> None:
...         pass
...
>>> # Create an SensorMethod instance
>>> bar_method = SensorMethod(Foo.bar)
>>>
>>> bar_method
SensorMethod(meth=<function Foo.bar at 0x...>)
__repr__()

Returns a string representation of the BaseSensor instance.

Returns:

The string representation of the instance.

Return type:

str

Examples

>>> class SomeInstrument:
...     pass
...
>>> # Define a class with a decorated method
>>> from domprob import sensor
>>>
>>> class Foo:
...     @sensor(SomeInstrument)
...     def bar(self, instrument: SomeInstrument) -> None:
...         pass
...
>>> # Create an SensorMethod instance
>>> bar_method = BaseSensorMethod(Foo.bar)
>>>
>>> repr(bar_method)
'BaseSensorMethod(meth=<function Foo.bar at 0x...>)'
_binder: SensorMethodBinder[ParamSpec(_PMeth, bound= None), TypeVar(_RMeth)]
_meth
_supp_instrums
bind(*args, **kwargs)[source]

Binds passed parameters to the method, returning a partially bound version.

This method partially binds the provided runtime arguments. It returns a BoundSensorMethod object that represents the partially bound method, which can later be executed with additional arguments if needed.

Parameters:
  • cls_instance (Any) – The class instance to bind. This is the self arg defined in instance methods.

  • *args (P.args) – Additional positional arguments to bind to the method.

  • **kwargs (P.kwargs) – Additional keyword arguments to bind to the method.

Returns:

A new wrapper representing a

partially bound method.

Return type:

BoundSensorMethod

Examples

>>> class SomeInstrument:
...     pass
...
>>> # Define a class with a decorated method
>>> from domprob import sensor
>>>
>>> class Foo:
...     @sensor(SomeInstrument)
...     def bar(self, instrum: SomeInstrument) -> None:
...         pass
...
>>> # Create an SensorMethod instance
>>> bar_method = SensorMethod(Foo.bar)
>>>
>>> # Create an instance of the class and instrument
>>> instrument_instance = SomeInstrument()
>>> foo = Foo()
>>>
>>> # Binds method with instrument instance
>>> args = (foo, instrument_instance)
>>> bound_method = bar_method.bind(*args)
>>> bound_method
BoundSensorMethod(sensor_meth=SensorMethod(meth=<function Foo.bar at 0x...>), bound_params=<BoundArguments (self=<domprob.sensors.meth.Foo object at 0x...>, instrum=<domprob.sensors.meth.SomeInstrument object at 0x...>)>)
classmethod from_callable(meth)[source]

Creates an SensorMethod instance from a callable if it supports instruments.

This class method checks if the provided callable (meth) has associated metadata for supported instruments. If it does, an SensorMethod instance is created and returned. Otherwise, None is returned.

Parameters:

meth (Callable[_PMeth, _RMeth]) – The method or function to be wrapped as an SensorMethod.

Returns:

  • An instance of SensorMethod if the callable has associated metadata.

  • None if the callable does not support instruments.

Return type:

SensorMethod[_PMeth, _RMeth] | None

Example

>>> from domprob import sensor
>>>
>>> class SomeInstrument:
...     pass
...
>>> class Foo:
...     @sensor(SomeInstrument)
...     def bar(self, instrument: SomeInstrument) -> None:
...         print(f"Instrument: {instrument}")
...
>>> # Create an SensorMethod instance from a method
>>> sensor_meth = SensorMethod.from_callable(Foo.bar)
>>> assert isinstance(sensor_meth, SensorMethod)
>>> print(sensor_meth)
SensorMethod(meth=<function Foo.bar at 0x...>)
>>> # Attempt to create an SensorMethod from a method without metadata
>>> def no_sensor_method():
...     pass
...
>>> assert SensorMethod.from_callable(no_sensor_method) is None
property is_static: bool

Determines whether the method is a static method.

This property inspects the method’s module, its qualified name, and dynamically created classes to infer whether it is a static method.

The method checks: 1. The module dictionary to locate the method’s enclosing

class.

  1. The local scope (locals()) to handle dynamically created classes.

  2. Uses getattr_static() to check if the method is explicitly declared as a staticmethod.

Returns:

True if the method can be detected as static,

otherwise False.

Return type:

bool

property meth: Callable[[_PMeth], _RMeth]

Returns the decorated method.

This method represents the underlying method associated with the sensors.

Returns:

The method associated with these

sensors.

Return type:

Callable[_PMeth, _RMeth]

Examples

>>> from domprob.sensors.meth import BaseSensorMethod
>>>
>>> def example_method():
...     pass
...
>>> base = BaseSensorMethod(example_method)
>>> base.meth
<function example_method at 0x...>
property sig: SensorMethodSignature[_PMeth, _RMeth]

Generates a SensorMethodSignature representation of the method.

This property extracts the method signature from the current sensor instance.

Returns:

The signature of the method.

Return type:

SensorMethodSignature

property supp_instrums: Instruments

Returns the supported instruments for this method.

This property retrieves the metadata associated with the decorated method, indicating which instruments are supported.

Returns:

An Instruments object containing metadata

about the method’s supported instruments.

Return type:

Instruments

Examples

>>> from domprob.sensors.meth import BaseSensorMethod
>>>
>>> class SomeInstrument:
...     pass
...
>>> def example_method(instrument: SomeInstrument) -> None:
...     pass
...
>>> base = BaseSensorMethod(example_method)
>>> base.supp_instrums
Instruments(metadata=SensorMetadata(method=<function example_method at 0x...>))
class domprob.sensors.meth_sig.InferSigInstrumBase(sig)[source]

Bases: ABC

Abstract base class for inferring the instrum parameter in a sensor method signature.

Subclasses implement different strategies for identifying and renaming the instrum parameter within a method signature.

sig

The method signature being analyzed.

Type:

SensorMethodSignature

__repr__()[source]

Returns a string representation of the inference object.

Returns:

Human readable string representation of the inferer.

Return type:

str

_abc_impl = <_abc._abc_data object>
abstract infer()[source]

Attempts to infer and rename the instrum parameter in the method signature.

Returns:

The updated signature if

inference is successful, otherwise None.

Return type:

SensorMethodSignature | None

sig
class domprob.sensors.meth_sig.InferSigInstrumByAnnotation(sig)[source]

Bases: InferSigInstrumBase

Infers the instrum parameter based on type annotations.

__repr__()

Returns a string representation of the inference object.

Returns:

Human readable string representation of the inferer.

Return type:

str

_abc_impl = <_abc._abc_data object>
_supp_instrums: tuple[Any, ...] | None
_type_hints: dict[str, Any] | None
get_type(param)[source]

Extracts the type annotation of a parameter.

Parameters:

param (Parameter) – The parameter object.

Returns:

The resolved type annotation, None if unavailable.

Return type:

Any

in_supp_instrums(param_type)[source]

Checks if a parameter type matches any of the supported instruments.

Parameters:

param_type (Any) – The parameter type to check.

Returns:

True if the type matches a supported instrument,

False otherwise.

Return type:

bool

infer()[source]

Infers the instrum parameter using type annotations.

First checks to see if the method is static. If the method is not static, ignores first param.

Warning

Returns None if there are more than one parameter type annotations that match the supported instruments.

Returns:

The updated signature if

inference is successful, otherwise None.

Return type:

SensorMethodSignature | None

sig
property supp_instrums: tuple[Any, ...]

Gets the supported instrument types extracted from the sensor method.

Returns:

A tuple of instrument types.

Return type:

tuple[Any, …]

property type_hints: dict[str, Any]

Retrieves type hints for the params defined in the sensor method.

Returns:

A dictionary of parameter names and their

corresponding type hints.

Return type:

dict[str, Any]

class domprob.sensors.meth_sig.InferSigInstrumByName(sig)[source]

Bases: InferSigInstrumBase

Infers the instrum parameter by checking for common name patterns.

__repr__()

Returns a string representation of the inference object.

Returns:

Human readable string representation of the inferer.

Return type:

str

_abc_impl = <_abc._abc_data object>
infer()[source]

Infers the instrum parameter based on ‘instrum’ or ‘instrument’ param name matching.

Returns:

The updated signature if

inference is successful, otherwise None.

Return type:

SensorMethodSignature | None

sig
class domprob.sensors.meth_sig.InferSigInstrumByPosition(sig)[source]

Bases: InferSigInstrumBase

Infers the instrum parameter based on its position in the signature.

__repr__()

Returns a string representation of the inference object.

Returns:

Human readable string representation of the inferer.

Return type:

str

_abc_impl = <_abc._abc_data object>
infer()[source]

Infers the instrum parameter based on position.

Assumes the second param is the instrument, or first param if sensor method is static.

Returns:

The updated signature if

inference is successful, otherwise None.

Return type:

SensorMethodSignature | None

sig
class domprob.sensors.meth_sig.SensorMethodSignature(parameters=None, *, return_annotation=None, __validate_parameters__=True)[source]

Bases: Signature, Generic[_P, _R]

Represents the inspect.Signature of a sensor method with extended functionality.

Provides utilities for parameter inference, renaming, and type extraction.

Parameters:
  • parameters (Sequence[Parameter] | None) – The method parameters.

  • return_annotation (Any, optional) – The return type annotation.

  • __validate_parameters__ (bool, optional) – Whether to validate parameters.

_INFERERS: tuple[type[InferSigInstrumBase], ...] = (<class 'domprob.sensors.meth_sig.InferSigInstrumByName'>, <class 'domprob.sensors.meth_sig.InferSigInstrumByAnnotation'>, <class 'domprob.sensors.meth_sig.InferSigInstrumByPosition'>)
__eq__(other)

Return self==value.

__len__()[source]

Returns the number of parameters in the method signature.

Returns:

The number of parameters.

Return type:

int

__repr__()

Return repr(self).

_bind(args, kwargs, *, partial=False)

Private method. Don’t use directly.

_bound_arguments_cls

alias of BoundArguments

_hash_basis()
_keys: tuple[str, ...] | None
_parameter_cls

alias of Parameter

_parameters
_params: tuple[Parameter, ...] | None
_return_annotation
_sensor: Optional[BaseSensorMethod[ParamSpec(_P, bound= None), TypeVar(_R)]]
bind(*args, **kwargs)

Get a BoundArguments object, that maps the passed args and kwargs to the function’s signature. Raises TypeError if the passed arguments can not be bound.

bind_partial(*args, **kwargs)

Get a BoundArguments object, that partially maps the passed args and kwargs to the function’s signature. Raises TypeError if the passed arguments can not be bound.

empty

alias of _empty

format(*, max_width=None)

Create a string representation of the Signature object.

If max_width integer is passed, signature will try to fit into the max_width. If signature is longer than max_width, all parameters will be on separate lines.

classmethod from_callable(obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)

Constructs Signature for the given callable object.

classmethod from_sensor(sensor, *, return_annotation=None, __validate_parameters__=True)[source]

Creates a signature instance from a sensor method.

Parameters:
  • sensor (BaseSensorMethod) – The sensor method to analyze.

  • return_annotation (Any, optional) – The return type annotation.

  • __validate_parameters__ (bool, optional) – Whether to validate the parameters, defaults to True.

Returns:

The generated signature instance.

Return type:

SensorMethodSignature

get_param(name)[source]

Retrieves a parameter by name.

Parameters:

name (str) – The name of the parameter to retrieve.

Raises:

ValueError – If the parameter is not found.

Returns:

The requested parameter object.

Return type:

Parameter

infer()[source]

Attempts to infer the instrum parameter using available inference strategies.

This method sequentially applies inference techniques to try to determine which parameter in the signature represents the instrument.

Returns:

A new signature after inference has

been attempted.

Return type:

SensorMethodSignature

property keys: tuple[str, ...]

Gets the names of parameters in the method signature.

Returns:

A tuple of parameter names.

Return type:

tuple[str, …]

property meth: Callable[[_P], _R]

Retrieves the sensor method.

Returns:

The sensor method.

Return type:

Callable[[Any], Any]

property parameters
replace(*, parameters=None, return_annotation=None)[source]

Creates a new, modified SensorMethodSignature instance.

Parameters:
  • parameters (Sequence[Parameter] | type[Any] | None, optional) – The updated parameters for the method signature.

  • return_annotation (Any, optional) – The updated return annotation.

Returns:

A new SensorMethodSignature instance with the

updated signature.

Return type:

Self

property return_annotation
rn_param(param, value)[source]

Renames a parameter in the method signature.

Parameters:
  • param (str | Parameter) – The parameter name or object to rename.

  • value (str) – The new name for the parameter.

Raises:

ValueError – If the new parameter name already exists.

Returns:

A new SensorMethodSignature instance with the

renamed parameter.

Return type:

Self

property sensor: BaseSensorMethod[_P, _R]

Gets the associated sensor method.

Raises:

ValueError – If the sensor method is not set during initialization.

Returns:

The sensor method associated with the

signature.

Return type:

BaseSensorMethod

update_param(*, old, new)[source]

Replaces an existing parameter with a new one.

Parameters:
  • old (Parameter) – The parameter to be replaced.

  • new (Parameter) – The new parameter object.

Returns:

A new SensorMethodSignature instance with the

updated parameter.

Return type:

Self

property values: tuple[Parameter, ...]

Gets the parameters in the method signature.

Returns:

A tuple of parameter objects.

Return type:

tuple[Parameter, …]

exception domprob.sensors.exc.SensorException[source]

Bases: DomprobException

Base exception class for errors related to the @sensor functionality.

This serves as a parent class for all exceptions raised within the sensors framework.

__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Validate

class domprob.sensors.validate.base_val.BaseValidator(next_=None)[source]

Bases: ABC

Abstract base class for creating validators in a chain of responsibility pattern.

This class defines a structure for implementing validate logic where each validator can perform a specific validate task and optionally pass the validate responsibility to the next validator in the chain. Subclasses must override the validate method to provide specific validate logic.

Parameters:

next (BaseValidator | None, optional) – The next validator in the chain. Defaults to None, indicating no further validate.

next_

Holds the reference to the next validator in the chain or None if this is the last validator.

Type:

BaseValidator | None

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.meth import SensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         if not method.instrum:
...             raise ValueError("Instrument is required")
...         print("Validation successful")
...         super().validate(method)
...
>>> # Mock setup for example
>>> class SomeInstrument:
...     pass
...
>>> class Cls:
...     def method(self, instrum: SomeInstrument) -> None:
...         pass
...
>>> meth = SensorMethod(Cls.method)
>>> bound_meth = meth.bind(Cls(), SomeInstrument())
>>> validator = ExampleValidator()
>>> validator.validate(bound_meth)
Validation successful
>>> # Chaining validators
>>> validator1 = ExampleValidator()
>>> validator2 = ExampleValidator(next_=validator1)
>>> validator2.validate(bound_meth)
Validation successful
Validation successful
__repr__()[source]

Returns a string representation of the validator.

This includes the class name and the next_ validator in the chain, making it easier to debug and inspect validator chains.

Returns:

A string representation of the validator.

Return type:

str

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.meth import BoundSensorMethod
>>> class ExampleValidator(BaseValidator):
...     def validate(self, meth: BoundSensorMethod) -> None:
...         pass
...
>>> validator = ExampleValidator(next_=None)
>>> repr(validator)
'ExampleValidator(next_=None)'
>>> chained_validator = ExampleValidator(next_=validator)
>>> repr(chained_validator)
'ExampleValidator(next_=ExampleValidator(next_=None))'
_abc_impl = <_abc._abc_data object>
abstract validate(b_meth)[source]

Validates a BoundSensorMethod instance.

This method performs the validate logic for the current validator and delegates to the next validator in the chain if one is defined. Subclasses must implement the specific validate logic by overriding this method.

Parameters:

b_meth (BoundSensorMethod) – Bound method wrapper to validate.

Raises:
  • ValidatorException – If the validate fails.

  • Exception – If an unexpected error occurs during validate.

Return type:

None

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.meth import SensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, meth: BoundSensorMethod) -> None:
...         if not meth.instrum:
...             raise ValidatorException("Instrument is required")
...         print("Validation successful")
...         super().validate(meth)
...
>>> # Mock setup for example
>>> class SomeInstrument:
...     pass
...
>>> class Cls:
...     def method(self, instrum: SomeInstrument) -> None:
...         pass
...
>>> meth = SensorMethod(Cls.method)
>>> bound_meth = meth.bind(Cls(), SomeInstrument())
>>> validator = ExampleValidator()
>>> validator.validate(bound_meth)
Validation successful
exception domprob.sensors.validate.base_val.ValidatorException[source]

Bases: SensorException

Exception raised when a validate error occurs in a validator.

This exception is used to indicate that validate has failed during the execution of a validate chain. It inherits from SensorException to ensure consistency in exception handling across the package.

__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class domprob.sensors.validate.chain.ValidationChain(base, *link_validators, validator_context=None)[source]

Bases: Generic[_ChainLink], MutableSequence[_ChainLink]

A class that represents a chain of validators for validating links.

The ValidationChain class manages a collection of validators that can sequentially validate links. It provides methods to add, insert, and remove validators, as well as to execute validations in a structured manner. The chain ensures type consistency and supports extensibility.

base

The expected base type for all links in the chain.

Type:

type

Parameters:
  • base (type) – The base type that all links in the chain must conform to.

  • *link_validators (ABCLinkValidator) – A list of validators in the chain.

  • validator_context (ABCLinkValidatorContext, optional) – The context in which the validators are validated.

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>> class ExampleValidator(ABCLinkValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> chain
ValidationChain(base='BaseValidator')
__contains__(item)[source]

Checks if a specific validator exists in the validate chain.

Parameters:

item (object) – The item to check for.

Returns:

True if the validator is in the chain, False otherwise.

Return type:

bool

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> "" in chain
False
>>> validator = ExampleValidator()
>>> chain.append(validator)
>>> validator in chain
True
__eq__(other)[source]

Compares two validate chains for equality.

Two validate chains are considered equal if they have the same base type and contain the same validators in the same order.

Parameters:

other (object) – The object to compare with.

Returns:

True if the chains are equal, False otherwise.

Return type:

bool

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain_1 = ValidationChain(BaseValidator)
>>> chain_2 = ValidationChain(BaseValidator)
>>> chain_1 == chain_2
True
>>> chain_1 == ""
False
>>> chain_1.append(ExampleValidator())
>>> chain_1 == chain_2
False
__iter__()[source]

Returns an iterator over the validators in the validate chain.

This method allows the validate chain to be iterated over directly, returning each validator in sequence.

Returns:

An iterator over the

validators.

Return type:

Iterator[ABCLinkValidator]

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> chain.append(ExampleValidator())
>>> chain.append(ExampleValidator())
>>>
>>> for link in chain:
...     repr(link)
...
'ExampleValidator(next_=ExampleValidator(next_=None))'
'ExampleValidator(next_=None)'
__len__()[source]

Returns the number of validators in the validate chain.

This method allows the use of the len() function to determine how many validators are in the chain.

Returns:

The number of validators in the chain.

Return type:

int

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> len(chain)
0
>>> chain.append(ExampleValidator())
>>> len(chain)
1
__repr__()[source]

Returns a string representation of the ValidationChain instance.

Returns:

A string representation of the ValidationChain.

Return type:

str

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> chain = ValidationChain(BaseValidator)
>>> repr(chain)
"ValidationChain(base='BaseValidator')"
_abc_impl = <_abc._abc_data object>
_delete_single_item(index, /)[source]

Handles deletion for a single element.

Return type:

None

_delete_slice_items(index, /)[source]
Return type:

None

Return type:

None

_set_single_item(index, link, /)[source]
Return type:

None

_set_slice_items(index, links, /)[source]
Return type:

None

append(value)[source]

Adds a validator to the end of the validate chain.

This method allows adding a new validator to the chain, ensuring it follows the chain’s base type requirements.

Parameters:

value (BaseValidator) – The validator to add to the chain.

Raises:

TypeError – If the provided validator is not an instance of self.base.

Examples

Return type:

None

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> chain.append(ExampleValidator())
clear()[source]

Removes all validators from the validate chain.

Return type:

None

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> chain.append(ExampleValidator())
>>> chain.append(ExampleValidator())
>>> len(chain)
2
>>> chain.clear()
>>> len(chain)
0
count(value) integer -- return number of occurrences of value
extend(values)[source]

Adds multiple validators to the end of the validate chain.

This method appends a list of validators to the chain. It ensures that each validator conforms to the chain’s base type requirements.

Parameters:

values (Iterable[BaseValidator]) – An iterable of validators to add to the chain.

Raises:

TypeError – If any of the provided validators are not instances of self.base.

Examples

Return type:

None

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> chain.extend([ExampleValidator(), ExampleValidator()])
>>> len(chain)
2
index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(index, value)[source]

Inserts a validator at the specified index in the validate chain.

This method adds a new validator at a specific position in the chain, shifting subsequent validators to the right.

Parameters:
  • index (int) – The position to insert the validator.

  • value (BaseValidator) – The validator to insert.

Raises:

TypeError – If the provided validator is not an instance of self.base.

Examples

Return type:

None

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, method: BoundSensorMethod) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> chain.insert(0, ExampleValidator())
>>> len(chain)
1
pop([index]) item -- remove and return item at index (default last).

Raise IndexError if list is empty or index is out of range.

remove(value)

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()

S.reverse() – reverse IN PLACE

validate_chain(*args, **kwargs)[source]

Validates the entire chain to ensure it meets the base type requirements.

This method checks that all validators in the chain are valid and comply with the chain’s expected rules. It raises an exception if any validator is invalid.

Return type:

None

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.meth import BoundSensorMethod
>>>
>>> chain = ValidationChain(BaseValidator)
>>> try:
...     chain.validate_chain()
... except EmptyChainException as e:
...     print(e)
...
Nothing to validate, no links added to chain 'ValidationChain(base='BaseValidator')'
class domprob.sensors.validate.chain_val.ABCLinkValidator(chain)[source]

Bases: ABC

Abstract base class for validators in a validate chain.

This class defines the structure for implementing validators that perform specific checks on links within a validate chain.

chain

The validate chain associated with this validator. It provides context for the validate process.

Type:

ValidationChain

Parameters:

chain (ValidationChain) – The validate chain to associate with this validator.

Examples

>>> from domprob.sensors.validate.chain import ABCLinkValidator
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> class ExampleValidator(ABCLinkValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
__repr__()[source]

Returns a string representation of the validator.

Returns:

A string representation of the validator, including

its class name and the validate chain it belongs to.

Return type:

str

Examples

>>> from domprob.sensors.validate.chain import ABCLinkValidator
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> class ExampleValidator(ABCLinkValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> from domprob.sensors.validate.chain import ValidationChain
>>>
>>> validator = ExampleValidator(ValidationChain(BaseValidator))
>>> repr(validator)
"ExampleValidator(ValidationChain(base='BaseValidator'))"
_abc_impl = <_abc._abc_data object>
abstract validate(link)[source]

Validates a single link in the validate chain.

This abstract method must be implemented by subclasses to define specific validate logic.

Parameters:

link (_ChainLink) – The link to validate.

Raises:

NotImplementedError – If the subclass does not implement this method.

Return type:

None

class domprob.sensors.validate.chain_val.ABCLinkValidatorContext(chain, *validators)[source]

Bases: ABC

Abstract base class for context-aware link validators in a validate chain.

This class provides an interface for validators that need additional context about the validate chain during the validate process. It enforces the implementation of the validate method, allowing subclasses to perform more sophisticated validations that depend on the state of the chain.

chain

The validate chain associated with this validator. It provides context for the validate process.

Type:

ValidationChain

Parameters:

chain (ValidationChain) – The validate chain to associate with this context-aware validator.

Examples

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>>
>>> class ExampleContext(ABCLinkValidatorContext):
...     def add_validators(self, *validators: type[BaseValidator]) -> None:
...         pass
...
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> validator_context = ExampleContext(chain)
>>> validator_context.validate(ExampleValidator())
__repr__()[source]

Returns a string representation of the context-aware validator.

Returns:

A string representation of the validator, showing the

class name and the validate chain it is associated with.

Return type:

str

Examples

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext,
...     BaseValidator,
...     ValidationChain
... )
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> class ExampleContext(ABCLinkValidatorContext):
...     def add_validators(self, *validators: type[BaseValidator]) -> None:
...         pass
...
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> chain = ValidationChain(ExampleValidator)
>>> context = ExampleContext(chain)
>>> repr(context)
"ExampleContext(chain=ValidationChain(base='ExampleValidator'))"
_abc_impl = <_abc._abc_data object>
abstract add_validators(*validators)[source]

Adds one or more validators to the validate chain.

This abstract method is designed to allow additional validators to be dynamically added to the validate chain during runtime. Each validator is appended to the chain, enabling customisation and extensibility of the validate process.

Parameters:

*validators (ABCLinkValidator) – One or more validator instances to add to the validate chain.

Return type:

None

Examples

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> class ExampleContext(ABCLinkValidatorContext):
...     def add_validators(self, *validators: type[BaseValidator]) -> None:
...         pass
...
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> chain = ValidationChain(ExampleValidator)
>>> context = ExampleContext(chain)
>>> context.add_validators(ExampleValidator, ExampleValidator)
abstract validate(link)[source]

Abstract method to validate a link in the chain using additional context.

This method must be implemented by subclasses to provide logic for validating a link with additional contextual information. This allows the validator to account for dynamic rules or states during validate.

Parameters:

link (_ChainLink) – The link to validate.

Raises:

NotImplementedError – If a subclass does not implement this method.

Examples

Return type:

None

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>>
>>> class ExampleContext(ABCLinkValidatorContext):
...     def add_validators(self, *validators: type[BaseValidator]) -> None:
...         pass
...
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> chain = ValidationChain(ExampleValidator)
>>> validator_context = ExampleContext(chain)
>>> validator_context.validate(ExampleValidator())
exception domprob.sensors.validate.chain_val.EmptyChainException(chain)[source]

Bases: ValidationChainException

Exception raised when a validate chain is empty.

This exception indicates that no validators have been added to a validate chain, which prevents the chain from performing any meaningful validate.

Parameters:

chain (ValidationChain) – The empty validate chain.

chain

The empty validate chain.

Type:

ValidationChain

Examples

>>> from domprob.exceptions import EmptyChainException
>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>>
>>> try:
...     raise EmptyChainException(ValidationChain(BaseValidator))
... except EmptyChainException as e:
...     print(e)
...
Nothing to validate, no links added to chain 'ValidationChain(base='BaseValidator')'
__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
property msg: str

Returns the error message associated with the exception.

Returns:

The error message describing the empty validate

chain issue.

Return type:

str

Examples

>>> from domprob.exceptions import EmptyChainException
>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>>
>>> exc = EmptyChainException(ValidationChain(BaseValidator))
>>> exc.msg
"Nothing to validate, no links added to chain 'ValidationChain(base='BaseValidator')'"
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception domprob.sensors.validate.chain_val.InvalidLinkException(link, expected_type)[source]

Bases: ValidationChainException

Exception raised when an invalid link is added to a validate chain.

This exception is used to indicate that a link in the validate chain does not meet the required criteria or fails validate. It provides detailed information about the invalid link and the expected type.

The invalid link that caused the exception.

Type:

Any

expected_type

The expected type for valid links in the chain.

Type:

type[Any]

Parameters:
  • link (Any) – The link object that is invalid.

  • expected_type (type[Any]) – The expected type for links in the validate chain.

Examples

>>> from domprob.exceptions import InvalidLinkException
>>>
>>> def raise_invalid_link():
...     raise InvalidLinkException("InvalidLink", expected_type=int)
...
>>> try:
...     raise_invalid_link()
... except InvalidLinkException as e:
...     print(str(e))
Invalid link of type 'str', expected type 'int'
__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
property msg: str

Constructs a detailed error message for the exception.

This property dynamically generates a human-readable string that describes the invalid link and the expected type.

Returns:

A string describing the invalid link and its expected

type.

Return type:

str

Examples

>>> exc = InvalidLinkException("InvalidLink", expected_type=int)
>>> exc.msg
"Invalid link of type 'str', expected type 'int'"
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception domprob.sensors.validate.chain_val.LinkExistsException(link, chain)[source]

Bases: ValidationChainException

Exception raised when a duplicate link is added to a validate chain.

This exception is used to indicate that the specified link already exists in the validate chain and duplicates are not allowed. It provides details about the duplicate link and the chain where the conflict occurred.

Parameters:
  • link (Any) – The duplicate link that caused the exception.

  • chain (ValidationChain) – The validate chain where the duplicate was found.

The duplicate link.

Type:

Any

chain

The chain where the duplicate was detected.

Type:

ValidationChain

Examples

>>> from domprob.exceptions import LinkExistsException
>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>>
>>> try:
...     raise LinkExistsException("DuplicateLink", chain=ValidationChain(BaseValidator))  # type: ignore
... except LinkExistsException as e:
...     print(e)
...
Link ''DuplicateLink'' already exists in chain 'ValidationChain(base='BaseValidator')'
__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
property msg: str

Constructs a detailed error message indicating a duplicate link in the validate chain.

Returns:

A message indicating the duplicate link and the

affected chain.

Return type:

str

Examples

>>> from domprob.exceptions import LinkExistsException
>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>>
>>> chain = ValidationChain(base=BaseValidator)
>>> exc = LinkExistsException("DuplicateLink", chain)  # type: ignore
>>> exc.msg
"Link ''DuplicateLink'' already exists in chain 'ValidationChain(base='BaseValidator')'"
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class domprob.sensors.validate.chain_val.LinkTypeValidator(chain)[source]

Bases: ABCLinkValidator

Validator to ensure that links in the validate chain are of the expected type.

This validator checks whether each link added to the validate chain is an instance of the chain’s base type. If a link does not match the expected type, it raises an InvalidLinkException. This ensures type safety and consistency within the chain.

chain

The validate chain this validator is associated with.

Type:

ValidationChain

Examples

>>> from domprob.sensors.validate.chain_val import LinkTypeValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> validator = LinkTypeValidator(ValidationChain(BaseValidator))
>>>
>>> try:
...     validator.validate(123)  # type: ignore
... except InvalidLinkException as e:
...     print(e)
...
Invalid link of type 'int', expected type 'BaseValidator'
__repr__()

Returns a string representation of the validator.

Returns:

A string representation of the validator, including

its class name and the validate chain it belongs to.

Return type:

str

Examples

>>> from domprob.sensors.validate.chain import ABCLinkValidator
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> class ExampleValidator(ABCLinkValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> from domprob.sensors.validate.chain import ValidationChain
>>>
>>> validator = ExampleValidator(ValidationChain(BaseValidator))
>>> repr(validator)
"ExampleValidator(ValidationChain(base='BaseValidator'))"
_abc_impl = <_abc._abc_data object>
validate(link)[source]

Validates that the provided link is of the expected type.

This method ensures that the given link is an instance of the chain’s base type. If the link is not of the expected type, it raises an InvalidLinkException.

Parameters:

link (_ChainLink) – The link to validate.

Raises:

InvalidLinkException – If the link is not of the expected type.

Return type:

None

Examples

>>> from domprob.sensors.validate.chain_val import LinkTypeValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> validator = LinkTypeValidator(ValidationChain(BaseValidator))
>>>
>>> try:
...     validator.validate(123)  # type: ignore
... except InvalidLinkException as e:
...     print(e)
...
Invalid link of type 'int', expected type 'BaseValidator'
class domprob.sensors.validate.chain_val.LinkValidatorContext(chain, *validators)[source]

Bases: ABCLinkValidatorContext

Concrete implementation of a context-aware link validator.

The LinkValidatorContext class extends ABCLinkValidatorContext to provide validate logic for links in a chain, utilising additional contextual information. It allows flexible and dynamic validate of links, depending on the state of the chain or external conditions.

chain

The validate chain associated with this context-aware validator.

Type:

ValidationChain

Parameters:

chain (ValidationChain) – The validate chain to associate with the validator.

Examples

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>> from domprob.sensors.validate.chain_val import InvalidLinkException
>>>
>>> class ExampleLink:
...     pass
...
>>> chain = ValidationChain(BaseValidator)
>>> validator_context = LinkValidatorContext(chain)
>>> try:
...     validator_context.validate("invalid_link")  # type: ignore
... except InvalidLinkException as e:
...     print(e)
Invalid link of type 'str', expected type 'BaseValidator'
DEFAULT_VALIDATORS: tuple[type[ABCLinkValidator], ...] = (<class 'domprob.sensors.validate.chain_val.LinkTypeValidator'>, <class 'domprob.sensors.validate.chain_val.UniqueLinkValidator'>)
__repr__()[source]

Returns a string representation of the LinkValidatorContext.

Returns:

A string representation of the context, including its

class name and the associated validate chain.

Return type:

str

Examples

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>>
>>> class ExampleLink:
...     pass
...
>>> chain = ValidationChain(BaseValidator)
>>> validator_context = LinkValidatorContext(chain)
>>> repr(validator_context)
"LinkValidatorContext(ValidationChain(base='BaseValidator'))"
_abc_impl = <_abc._abc_data object>
add_validators(*validators)[source]

Adds one or more validators to the validate chain.

This method allows the dynamic addition of validators to the validate chain at runtime. Each provided validator is appended to the chain, enabling custom validate logic and extensibility.

Parameters:

*validators (ABCLinkValidator) – One or more validator instances to add to the validate chain.

Return type:

None

Examples

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> class ExampleValidator(ABCLinkValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> chain = ValidationChain(BaseValidator)
>>> context = LinkValidatorContext(chain)
>>> context.add_validators(ExampleValidator, ExampleValidator)
validate(*links)[source]

Validates a link in the chain.

This method performs validate on the given links using the validators in the validate chain. It ensures that the link meets all the criteria enforced by the chain’s validators.

Parameters:

*links (_ChainLink) – The links to validate.

Raises:

Any – Exceptions raised by the individual validators in the chain if the link does not meet the required criteria.

Examples

Return type:

None

>>> from domprob.sensors.validate.chain import (
...     ABCLinkValidatorContext, ValidationChain
... )
>>> from domprob.sensors.validate.chain_val import InvalidLinkException
>>>
>>> class ExampleLink:
...     pass
...
>>> chain = ValidationChain(BaseValidator)
>>> validator_context = LinkValidatorContext(chain)
>>> try:
...     validator_context.validate("invalid_link")  # type: ignore
... except InvalidLinkException as e:
...     print(e)
Invalid link of type 'str', expected type 'BaseValidator'
validators: list[type[ABCLinkValidator]]
class domprob.sensors.validate.chain_val.UniqueLinkValidator(chain)[source]

Bases: ABCLinkValidator

Validator to ensure that links in the validate chain are unique.

This validator checks whether a link already exists in the validate chain. If a duplicate link is detected, it raises a LinkExistsException. This ensures that all links in the chain are unique.

chain

The validate chain this validator is associated with.

Type:

ValidationChain

Examples

>>> from domprob.sensors.validate.chain_val import LinkTypeValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> chain = ValidationChain(BaseValidator)
>>> validator = UniqueLinkValidator(chain)
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> example_validator = ExampleValidator()
>>> chain.append(example_validator)
>>>
>>> try:
...     validator.validate(example_validator)
... except LinkExistsException as e:
...     print(e)
...
Link 'ExampleValidator(next_=None)' already exists in chain 'ValidationChain(base='BaseValidator')'
__repr__()

Returns a string representation of the validator.

Returns:

A string representation of the validator, including

its class name and the validate chain it belongs to.

Return type:

str

Examples

>>> from domprob.sensors.validate.chain import ABCLinkValidator
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> class ExampleValidator(ABCLinkValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> from domprob.sensors.validate.chain import ValidationChain
>>>
>>> validator = ExampleValidator(ValidationChain(BaseValidator))
>>> repr(validator)
"ExampleValidator(ValidationChain(base='BaseValidator'))"
_abc_impl = <_abc._abc_data object>
validate(link)[source]

Validates that the provided link does not already exist in the validate chain.

This method checks whether the given link is already present in the validate chain. If the link is a duplicate, it raises a LinkExistsException. This ensures that all links within the chain are unique.

Parameters:

link (_ChainLink) – The link to validate.

Raises:

LinkExistsException – If the link already exists in the validate chain.

Return type:

None

Examples

>>> from domprob.sensors.validate.chain_val import LinkTypeValidator
>>> from domprob.sensors.validate.chain import ValidationChain
>>> from domprob.sensors.validate.base_val import BaseValidator
>>>
>>> chain = ValidationChain(BaseValidator)
>>> validator = UniqueLinkValidator(chain)
>>>
>>> class ExampleValidator(BaseValidator):
...     def validate(self, link: BaseValidator) -> None:
...         pass
...
>>> example_validator = ExampleValidator()
>>> chain.append(example_validator)
>>>
>>> try:
...     validator.validate(example_validator)
... except LinkExistsException as e:
...     print(e)
...
Link 'ExampleValidator(next_=None)' already exists in chain 'ValidationChain(base='BaseValidator')'
exception domprob.sensors.validate.chain_val.ValidationChainException[source]

Bases: SensorException

Base exception class for errors related to validate chains.

This exception serves as the root for all validate chain-related errors, such as issues with chain construction, execution, or invalid links. It is designed to be extended by more specific exceptions within the validate framework.

__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class domprob.sensors.validate.orch.SensorValidationOrchestrator(chain=None)[source]

Bases: object

Orchestrates validation of BoundSensorMethod instances using a chain of validators.

The orchestrator is initialised with a ValidationChain, which can either be customised or use the default set of validators. Validators are applied sequentially to ensure that the BoundSensorMethod adheres to defined rules and constraints.

DEFAULT_VALIDATORS

A tuple of default validator classes used to initialise the chain.

Type:

tuple[type[BaseValidator], …]

_chain

The validate chain that manages the sequence of validators.

Type:

ValidationChain

Parameters:

chain (ValidationChain | None, optional) – A custom validate chain. If not provided, a default chain is created with DEFAULT_VALIDATORS.

Examples

>>> from domprob.sensors.validate.orch import SensorValidationOrchestrator
>>> from domprob.sensors.meth import SensorMethod
>>>
>>> class SomeInstrument:
...     pass
...
>>> class Example:
...     def method(self, instrument: SomeInstrument) -> None:
...         pass
...
>>> method = SensorMethod(Example.method)
>>> method.supp_instrums.record(SomeInstrument, required=True)
Instruments(metadata=SensorMetadata(method=<function Example.method at 0x...>))
>>>
>>> bound_method = method.bind(Example(), SomeInstrument())
>>>
>>> orchestrator = SensorValidationOrchestrator()
>>> orchestrator.validate(bound_method)
DEFAULT_VALIDATORS: tuple[type[BaseValidator], ...] = (<class 'domprob.sensors.validate.vals.SupportedInstrumentsExistValidator'>, <class 'domprob.sensors.validate.vals.InstrumentParamExistsValidator'>, <class 'domprob.sensors.validate.vals.InstrumentTypeValidator'>)
__repr__()[source]

Returns a string representation of the orchestrator.

The representation includes the class name and the associated validate chain.

Returns:

A string representation of the orchestrator.

Return type:

str

Examples

>>> orchestrator = SensorValidationOrchestrator()
>>> repr(orchestrator)
"SensorValidationOrchestrator(ValidationChain(base='BaseValidator'))"
register(*validators)[source]

Registers additional validators to the validate chain.

Validators are appended to the existing chain, and their instances are created dynamically.

Parameters:

*validators (type[BaseValidator]) – Validator classes to be added to the chain.

Return type:

SensorValidationOrchestrator

Examples

>>> from domprob.sensors.validate.orch import SensorValidationOrchestrator
>>> from domprob.sensors.validate.vals import InstrumentTypeValidator
>>>
>>> orchestrator = SensorValidationOrchestrator()
>>> orchestrator.register(InstrumentTypeValidator)
SensorValidationOrchestrator(ValidationChain(base='BaseValidator'))
validate(method)[source]

Executes the validate chain on a BoundSensorMethod instance.

This method ensures that all registered validators are applied sequentially to the method.

Parameters:

method (BoundSensorMethod) – The method instance to validate.

Raises:

ValidatorException – If any of the validators in the chain fails.

Examples

>>> from domprob.sensors.validate.orch import SensorValidationOrchestrator
>>> from domprob.sensors.meth import SensorMethod
>>>
>>> class SomeInstrument:
...     pass
...
>>> class Example:
...     def method(self, instrument: SomeInstrument) -> None:
...         pass
...
>>> meth = SensorMethod(Example.method)
>>> bound_meth = meth.bind(Example(), SomeInstrument())
>>> bound_meth.supp_instrums.record(SomeInstrument, required=True)
Instruments(metadata=SensorMetadata(method=<function Example.method at 0x...>))
>>>
>>> orchestrator = SensorValidationOrchestrator()
>>> orchestrator.validate(bound_meth)
exception domprob.sensors.validate.vals.InstrumTypeException(b_meth)[source]

Bases: ValidatorException

Exception raised when the instrum parameter does not match the expected type.

Parameters:

b_meth (BoundSensorMethod) – Bound method that failed validate.

method

The method that failed validate.

Type:

Callable[…, Any]

instrum

The invalid instrument instance.

Type:

Any

supp_instrums

The supported instrument types.

Type:

Instruments

Examples

>>> from domprob.sensors.meth import SensorMethod
>>>
>>> class SomeInstrument:
...     pass
...
>>> class Example:
...     def method(self, instrum: SomeInstrument) -> None:
...         pass
...
>>> meth = SensorMethod(Example.method)
>>> meth.supp_instrums.record(SomeInstrument, True)
Instruments(metadata=SensorMetadata(method=<function Example.method at 0x...))
>>> bound_meth = meth.bind(Example(), 'InvalidInstrument')  # type: ignore
>>>
>>> try:
...     raise InstrumTypeException(bound_meth)
... except InstrumTypeException as e:
...     print(f"Error: {e}")
...
Error: Example.method(...) expects 'instrum' param to be one of: [SomeInstrument], but got: 'InvalidInstrument'
__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
property msg: str

Constructs a detailed error message.

Returns:

Error message describing the invalid instrument.

Return type:

str

with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class domprob.sensors.validate.vals.InstrumentParamExistsValidator(next_=None)[source]

Bases: BaseValidator

Validator to check if the instrum parameter exists.

This validator raises a MissingInstrumException if the instrum parameter is None.

Examples

>>> from domprob.sensors.validate.vals import InstrumentParamExistsValidator
>>> from domprob.sensors.meth import SensorMethod
>>>
>>> class SomeInstrument:
...     pass
...
>>> class Example:
...     def method(self, instrum: SomeInstrument) -> None:
...         pass
...
>>> meth = SensorMethod(Example.method)
>>> bound_meth = meth.bind(Example())  # type: ignore
>>>
>>> validator = InstrumentParamExistsValidator()
>>> try:
...     validator.validate(bound_meth)
... except MissingInstrumException as e:
...     print(f"Error: {e}")
...
Error: 'instrum' param missing in Example.method(...)
__repr__()

Returns a string representation of the validator.

This includes the class name and the next_ validator in the chain, making it easier to debug and inspect validator chains.

Returns:

A string representation of the validator.

Return type:

str

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.meth import BoundSensorMethod
>>> class ExampleValidator(BaseValidator):
...     def validate(self, meth: BoundSensorMethod) -> None:
...         pass
...
>>> validator = ExampleValidator(next_=None)
>>> repr(validator)
'ExampleValidator(next_=None)'
>>> chained_validator = ExampleValidator(next_=validator)
>>> repr(chained_validator)
'ExampleValidator(next_=ExampleValidator(next_=None))'
_abc_impl = <_abc._abc_data object>
validate(b_meth)[source]

Validates the method to ensure the instrument parameter exists.

Parameters:

b_meth (BoundSensorMethod) – Method with bound params to validate.

Raises:

MissingInstrumentException – If the instrum parameter is None.

Return type:

None

class domprob.sensors.validate.vals.InstrumentTypeValidator(next_=None)[source]

Bases: BaseValidator

Validator to check if the instrum is of a valid type.

This validator raises an InstrumTypeException if the type of the instrum parameter is not one of the supported instrument types.

Examples

>>> from domprob.sensors.validate.vals import InstrumentTypeValidator
>>> from domprob.sensors.meth import SensorMethod
>>> class MockInstrument:
...     pass
...
>>> class Example:
...     def method(self, instrum: MockInstrument) -> None:
...         pass
...
>>> meth = SensorMethod(Example.method)
>>> bound_meth = meth.bind(Example(), 'InvalidInstrument')  # type: ignore
>>>
>>> validator = InstrumentTypeValidator()
>>> try:
...     validator.validate(bound_meth)
... except InstrumTypeException as e:
...     print(f"Error: {e}")
...
Error: Example.method(...) expects 'instrum' param to be one of: [], but got: 'InvalidInstrument'
__repr__()

Returns a string representation of the validator.

This includes the class name and the next_ validator in the chain, making it easier to debug and inspect validator chains.

Returns:

A string representation of the validator.

Return type:

str

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.meth import BoundSensorMethod
>>> class ExampleValidator(BaseValidator):
...     def validate(self, meth: BoundSensorMethod) -> None:
...         pass
...
>>> validator = ExampleValidator(next_=None)
>>> repr(validator)
'ExampleValidator(next_=None)'
>>> chained_validator = ExampleValidator(next_=validator)
>>> repr(chained_validator)
'ExampleValidator(next_=ExampleValidator(next_=None))'
_abc_impl = <_abc._abc_data object>
validate(b_meth)[source]

Validates the method by checking the type of the instrument parameter.

Parameters:

b_meth (BoundSensorMethod) – Method with bound params to validate.

Raises:

InstrumTypeException – If the instrum parameter is not an instance of any specified instrument classes.

Return type:

None

exception domprob.sensors.validate.vals.MissingInstrumException(method)[source]

Bases: ValidatorException

Exception raised when the instrument parameter is missing during a call to a method.

Parameters:

method (Callable[..., Any]) – The method where the missing instrum parameter was detected.

method

The method that caused the exception.

Type:

Callable[…, Any]

Examples

>>> from domprob.sensors.validate.vals import MissingInstrumException
>>> class Example:
...     def method(self):
...         pass
...
>>> try:
...     raise MissingInstrumException(Example().method)
... except MissingInstrumException as e:
...     print(f"Error: {e}")
...
Error: 'instrum' param missing in Example.method(...)
__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
property msg: str

Constructs a detailed error message.

Returns:

Error message indicating the missing instrument

parameter.

Return type:

str

Examples

>>> class Example:
...     def method(self):
...         pass
...
>>> exc = MissingInstrumException(Example().method)
>>> exc.msg
"'instrum' param missing in Example.method(...)"
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception domprob.sensors.validate.vals.NoSupportedInstrumsException(method)[source]

Bases: ValidatorException

Exception raised when no supported instruments are defined for a method.

This exception indicates that the method’s metadata does not include any supported instrument types, which is required for proper validate.

Parameters:

method (Callable[..., Any]) – The method where the missing supported instruments were detected.

method

The method that caused the exception.

Type:

Callable[…, Any]

Examples

>>> from domprob.sensors.validate.vals import NoSupportedInstrumsException
>>> class Example:
...     def method(self):
...         pass
...
>>> try:
...     raise NoSupportedInstrumsException(Example().method)
... except NoSupportedInstrumsException as e:
...     print(f"Error: {e}")
...
Error: Example.method(...) has no supported instrument types defined
__repr__()

Return repr(self).

add_note(object, /)

Exception.add_note(note) – add a note to the exception

args
property msg: str

Constructs a detailed error message.

Returns:

Error message indicating that no supported instrument

types are defined for the method.

Return type:

str

Examples

>>> class Example:
...     def method(self):
...         pass
...
>>> exc = NoSupportedInstrumsException(Example().method)
>>> exc.msg
'Example.method(...) has no supported instrument types defined'
with_traceback(object, /)

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class domprob.sensors.validate.vals.SupportedInstrumentsExistValidator(next_=None)[source]

Bases: BaseValidator

Validator to ensure that at least one supported instrument is defined.

This validator raises a NoSupportedInstrumentsException if the method’s metadata does not include any supported instrument types.

Examples

>>> from domprob.sensors.validate.vals import SupportedInstrumentsExistValidator
>>> from domprob.sensors.meth import SensorMethod
>>> class Example:
...     def method(self, instrument: Any) -> None:
...         pass
...
>>> meth = SensorMethod(Example.method)
>>> bound_meth = meth.bind(Example())
>>>
>>> validator = SupportedInstrumentsExistValidator()
>>> try:
...     validator.validate(bound_meth)
... except NoSupportedInstrumsException as e:
...     print(f"Error: {e}")
...
Error: Example.method(...) has no supported instrument types defined
__repr__()

Returns a string representation of the validator.

This includes the class name and the next_ validator in the chain, making it easier to debug and inspect validator chains.

Returns:

A string representation of the validator.

Return type:

str

Examples

>>> from domprob.sensors.validate.base_val import BaseValidator
>>> from domprob.sensors.meth import BoundSensorMethod
>>> class ExampleValidator(BaseValidator):
...     def validate(self, meth: BoundSensorMethod) -> None:
...         pass
...
>>> validator = ExampleValidator(next_=None)
>>> repr(validator)
'ExampleValidator(next_=None)'
>>> chained_validator = ExampleValidator(next_=validator)
>>> repr(chained_validator)
'ExampleValidator(next_=ExampleValidator(next_=None))'
_abc_impl = <_abc._abc_data object>
validate(b_meth)[source]

Validates the method by checking the type of the instrument parameter.

Parameters:

b_meth (BoundSensorMethod) – Method with bound params to validate.

Raises:

NoSupportedInstrumsException – If the instrum parameter is not an instance of any valid instrument classes.

Return type:

None