From 54abe880a91768f3bdb6744247898856511ebf29 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 23 Oct 2026 12:28:35 +0000 Subject: [PATCH 1/4] Use absolute cross-references in docstrings Since mkdocstrings-python 2.0.9, relative cross-references are expanded from the path where an object is defined, not where it is documented. All our public symbols are defined in private modules and re-exported from a public package, so the strict documentation build fails with 330 warnings, blocking the bump. Counting the dots from the private module would fix the build, but it ties the references to the private module layout, breaks them on older mkdocstrings-python versions, and can make references to inherited members silently link to the wrong class. Relative references are also hard to read in an IDE, and only work in projects rendering our inherited docstrings if they enable `relative_crossrefs` too. All relative references are converted to absolute references to the public path of their target, which don't depend on any of that. The targets were taken from what mkdocstrings-python 2.0.7 expanded each reference to, and apart from the reworded summaries mentioned below, the built documentation has the same links as before, with both mkdocstrings-python 2.0.7 and 2.0.9. The only exception are the 3 references in `ElectricalComponent` and `BaseElectricalComponentConnection` documenting inherited members, which used to link to the copy of the member in each subclass and now link to the member in the base class, where it is defined. A few references in docstrings that are not rendered (private attributes and a test) are converted too, using the target they were meant to point to. Paragraphs are rewrapped to fit the longer references, and the summaries that got too long are reworded, moving the reference to the body or leaving it to the `Args` or `Returns` section, which already had it in most cases. See frequenz-floss/frequenz-repo-config-python#655 for details. Signed-off-by: Leandro Lucarella --- src/frequenz/client/common/_datetime.py | 34 +++--- src/frequenz/client/common/_exception.py | 10 +- .../client/common/grid/_delivery_area.py | 37 +++--- .../grid/proto/v1alpha8/_delivery_area.py | 38 ++++--- src/frequenz/client/common/metrics/_bounds.py | 71 ++++++------ src/frequenz/client/common/metrics/_sample.py | 103 +++++++++-------- .../common/metrics/proto/v1alpha8/_bounds.py | 47 ++++---- .../common/metrics/proto/v1alpha8/_metric.py | 11 +- .../v1alpha8/_metric_connection_category.py | 7 +- .../common/metrics/proto/v1alpha8/_sample.py | 55 +++++---- .../client/common/microgrid/_lifetime.py | 71 ++++++------ .../client/common/microgrid/_microgrid.py | 78 +++++++------ .../_electrical_component.py | 50 +++++---- .../_electrical_component_connection.py | 39 ++++--- .../_problematic_connection.py | 14 +-- .../proto/v1alpha8/_category.py | 8 +- .../proto/v1alpha8/_diagnostic_code.py | 4 +- .../proto/v1alpha8/_electrical_component.py | 25 ++--- .../proto/v1alpha8/_state_code.py | 8 +- .../microgrid/proto/v1alpha8/_lifetime.py | 10 +- .../microgrid/proto/v1alpha8/_microgrid.py | 5 +- .../common/microgrid/sensors/_sensor.py | 10 +- .../sensors/proto/v1alpha8/_sensor.py | 10 +- .../common/pagination/_pagination_info.py | 36 +++--- .../proto/v1alpha8/_pagination_info.py | 37 +++--- src/frequenz/client/common/proto/_datetime.py | 14 +-- .../common/streaming/proto/v1alpha8/_event.py | 11 +- .../client/common/test/enum_parity.py | 40 ++++--- src/frequenz/client/common/types/_location.py | 105 ++++++++++-------- .../common/types/proto/v1alpha8/_location.py | 16 +-- .../grid/_delivery_area/test_delivery_area.py | 13 ++- 31 files changed, 556 insertions(+), 461 deletions(-) diff --git a/src/frequenz/client/common/_datetime.py b/src/frequenz/client/common/_datetime.py index 40f8e92b..e07c8ce4 100644 --- a/src/frequenz/client/common/_datetime.py +++ b/src/frequenz/client/common/_datetime.py @@ -12,17 +12,18 @@ class InvalidDatetime: """A wire timestamp with no [`datetime`][datetime.datetime] equivalent. - A protobuf `Timestamp` counts whole [`seconds`][.seconds] since the Unix - epoch plus a fraction in [`nanos`][.nanos]. Both are plain integers on the - wire, so a decoded message can carry a value with no meaningful - [`datetime`][datetime.datetime]: - - - a [`seconds`][.seconds] count outside the years 1 to 9999, which is both - the range the protobuf specification allows and the range - [`datetime`][datetime.datetime] covers; - - a [`nanos`][.nanos] fraction outside `[0, 999999999]`, which the - protobuf specification does not allow and whose intended meaning is - therefore unknown. + A protobuf `Timestamp` counts whole + [`seconds`][frequenz.client.common.InvalidDatetime.seconds] since the Unix epoch + plus a fraction in [`nanos`][frequenz.client.common.InvalidDatetime.nanos]. Both are + plain integers on the wire, so a decoded message can carry a value with no + meaningful [`datetime`][datetime.datetime]: + + - a [`seconds`][frequenz.client.common.InvalidDatetime.seconds] count outside the + years 1 to 9999, which is both the range the protobuf specification allows and the + range [`datetime`][datetime.datetime] covers; + - a [`nanos`][frequenz.client.common.InvalidDatetime.nanos] fraction outside `[0, + 999999999]`, which the protobuf specification does not allow and whose intended + meaning is therefore unknown. This wrapper keeps both raw numbers unchanged so callers can inspect, report, or reinterpret what the server sent, instead of losing the message @@ -34,7 +35,10 @@ class InvalidDatetime: """The raw number of seconds since 1970-01-01T00:00:00Z.""" nanos: int - """The raw fraction of a second, in nanoseconds, to add to [`seconds`][..seconds].""" + """The raw fraction of a second, in nanoseconds. + + It is added to [`seconds`][frequenz.client.common.InvalidDatetime.seconds]. + """ def __str__(self) -> str: """Return a compact representation flagging this as an invalid value.""" @@ -44,9 +48,9 @@ def __str__(self) -> str: class InvalidDatetimeError(InvalidAttributeError): """Raised when a semantic accessor sees a timestamp with no `datetime` equivalent. - The offending [`InvalidDatetime`][..InvalidDatetime] is available as the - [`datetime`][.datetime] attribute so callers can inspect the raw wire - data. + The offending [`InvalidDatetime`][frequenz.client.common.InvalidDatetime] is + available as the [`datetime`][frequenz.client.common.InvalidDatetimeError.datetime] + attribute so callers can inspect the raw wire data. This is also a [`ValueError`][] for convenience. """ diff --git a/src/frequenz/client/common/_exception.py b/src/frequenz/client/common/_exception.py index 54313175..330ef28e 100644 --- a/src/frequenz/client/common/_exception.py +++ b/src/frequenz/client/common/_exception.py @@ -41,10 +41,10 @@ def __init__( class UnrecognizedEnumValueError(InvalidAttributeError): """Raised when a semantic accessor sees an unrecognized protobuf enum value. - This happens when the server sets an enum value that this version of the - client does not recognize, as opposed to an unspecified value (see - [`UnspecifiedEnumValueError`][..UnspecifiedEnumValueError]). The raw - unrecognized value is available as `value`. + This happens when the server sets an enum value that this version of the client does + not recognize, as opposed to an unspecified value (see + [`UnspecifiedEnumValueError`][frequenz.client.common.UnspecifiedEnumValueError]). + The raw unrecognized value is available as `value`. This is also a ``ValueError`` for convenience. """ @@ -79,7 +79,7 @@ class UnspecifiedEnumValueError(InvalidAttributeError): """Raised when a semantic accessor sees an unspecified protobuf enum value. For a value that is set but not recognized by this client, see - [`UnrecognizedEnumValueError`][..UnrecognizedEnumValueError]. + [`UnrecognizedEnumValueError`][frequenz.client.common.UnrecognizedEnumValueError]. This is also a [`ValueError`][] for convenience. """ diff --git a/src/frequenz/client/common/grid/_delivery_area.py b/src/frequenz/client/common/grid/_delivery_area.py index c51ba40e..7039a1df 100644 --- a/src/frequenz/client/common/grid/_delivery_area.py +++ b/src/frequenz/client/common/grid/_delivery_area.py @@ -63,10 +63,10 @@ class BaseDeliveryArea: """A base class for all delivery areas. This is the common supertype of both well-formed - [`DeliveryArea`][..DeliveryArea] instances and - [`InvalidDeliveryArea`][..InvalidDeliveryArea] instances that carry - malformed wire data. It cannot be instantiated directly; use one of - its concrete subclasses instead. + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea] instances and + [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea] instances + that carry malformed wire data. It cannot be instantiated directly; use one of its + concrete subclasses instead. """ code: str | None @@ -87,9 +87,9 @@ class BaseDeliveryArea: Tip: This is the lower-level accessor; when working with a valid - [`DeliveryArea`][...DeliveryArea], prefer - [`get_code_type`][...DeliveryArea.get_code_type] to obtain a known - member or a clear error. + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea], prefer + [`get_code_type`][frequenz.client.common.grid.DeliveryArea.get_code_type] to + obtain a known member or a clear error. """ # pylint: disable-next=unused-argument @@ -123,16 +123,17 @@ class DeliveryArea(BaseDeliveryArea): which they operate. Warning: Construction of invalid instances is deprecated - A well-formed `DeliveryArea` carries a non-empty [`code`][.code] and a - specified [`code_type`][.code_type]. Constructing one with data that - violates this invariant is **deprecated**, and will raise a + A well-formed `DeliveryArea` carries a non-empty + [`code`][frequenz.client.common.grid.DeliveryArea.code] and a specified + [`code_type`][frequenz.client.common.grid.DeliveryArea.code_type]. Constructing + one with data that violates this invariant is **deprecated**, and will raise a [`ValueError`][] in a future release. You can temporarily use the `_raise_on_invalid` keyword argument to get the upcoming behavior now (raising instead of deprecation warning). - Use [`InvalidDeliveryArea`][..InvalidDeliveryArea] if you need to - represent a malformed message. + Use [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea] if + you need to represent a malformed message. Note: Jurisdictional Differences This is typically represented by specific codes according to local jurisdiction. @@ -217,9 +218,9 @@ def get_code_type(self) -> EnergyMarketCodeType: class InvalidDeliveryArea(BaseDeliveryArea): """A delivery area with malformed data received from the wire. - Represents delivery area data that fails the invariants required for a - well-formed [`DeliveryArea`][..DeliveryArea]. Callers can inspect the raw - fields to recover partial information. + Represents delivery area data that fails the invariants required for a well-formed + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea]. Callers can inspect the + raw fields to recover partial information. This class does not enforce any invariants on construction. """ @@ -246,9 +247,9 @@ def __str__(self) -> str: class InvalidDeliveryAreaError(InvalidAttributeError): """Raised when a semantic accessor sees an invalid delivery area. - The offending [`InvalidDeliveryArea`][..InvalidDeliveryArea] instance - is available as the `delivery_area` attribute so callers can inspect - the raw wire data. + The offending + [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea] instance is + available as the `delivery_area` attribute so callers can inspect the raw wire data. This is also a [`ValueError`][] for convenience. """ diff --git a/src/frequenz/client/common/grid/proto/v1alpha8/_delivery_area.py b/src/frequenz/client/common/grid/proto/v1alpha8/_delivery_area.py index 131e591b..06bfedb7 100644 --- a/src/frequenz/client/common/grid/proto/v1alpha8/_delivery_area.py +++ b/src/frequenz/client/common/grid/proto/v1alpha8/_delivery_area.py @@ -24,8 +24,9 @@ def energy_market_code_type_from_proto( message: The protobuf message to convert. Returns: - The corresponding [`EnergyMarketCodeType`][....EnergyMarketCodeType] enum - member, or the raw [`int`][] if the protobuf value is not recognized. + The corresponding + [`EnergyMarketCodeType`][frequenz.client.common.grid.EnergyMarketCodeType] + enum member, or the raw [`int`][] if the protobuf value is not recognized. """ return enum_from_proto(message, EnergyMarketCodeType) @@ -33,10 +34,12 @@ def energy_market_code_type_from_proto( def energy_market_code_type_to_proto( code_type: EnergyMarketCodeType, ) -> delivery_area_pb2.EnergyMarketCodeType.ValueType: - """Convert a [`EnergyMarketCodeType`][....EnergyMarketCodeType] enum member to a protobuf value. + """Convert an enum member to a protobuf `EnergyMarketCodeType` value. Args: - code_type: The enum member to convert. + code_type: The + [`EnergyMarketCodeType`][frequenz.client.common.grid.EnergyMarketCodeType] + enum member to convert. Returns: The corresponding protobuf `EnergyMarketCodeType` value. @@ -52,20 +55,21 @@ def energy_market_code_type_to_proto( def delivery_area_from_proto( # noqa: DOC502 message: delivery_area_pb2.DeliveryArea, ) -> DeliveryArea: - """Convert a protobuf message to a [`DeliveryArea`][....DeliveryArea] object. + """Convert a protobuf message to a delivery area object. Warning: Deprecated - Use [`delivery_area_from_proto2`][..delivery_area_from_proto2] - instead. The new converter distinguishes well-formed from - malformed data at the type level - (`DeliveryArea | InvalidDeliveryArea`) rather than silently + Use + [`delivery_area_from_proto2`][frequenz.client.common.grid.proto.v1alpha8.delivery_area_from_proto2] + instead. The new converter distinguishes well-formed from malformed data at the + type level (`DeliveryArea | InvalidDeliveryArea`) rather than silently constructing a `DeliveryArea` with invalid content. Args: message: The protobuf message to convert. Returns: - The corresponding [`DeliveryArea`][....DeliveryArea] object. + The corresponding [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea] + object. """ issues: list[str] = [] @@ -105,10 +109,11 @@ def delivery_area_from_proto2( ) -> DeliveryArea | InvalidDeliveryArea: """Convert a protobuf message to a delivery area object. - A well-formed message becomes a [`DeliveryArea`][....DeliveryArea]; a - message that fails the `DeliveryArea` invariant becomes an - [`InvalidDeliveryArea`][....InvalidDeliveryArea] carrying the raw wire - data so callers can inspect or report it. + A well-formed message becomes a + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea]; a message that fails the + `DeliveryArea` invariant becomes an + [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea] carrying + the raw wire data so callers can inspect or report it. Unknown `int` `code_type` values are treated as valid to preserve forward compatibility with new protobuf enum values. @@ -123,8 +128,9 @@ def delivery_area_from_proto2( message: The protobuf message to convert. Returns: - A [`DeliveryArea`][....DeliveryArea] when the wire data is - well-formed, an [`InvalidDeliveryArea`][....InvalidDeliveryArea] + A [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea] when the wire data + is well-formed, an + [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea] otherwise. """ raw_code_type = message.code_type diff --git a/src/frequenz/client/common/metrics/_bounds.py b/src/frequenz/client/common/metrics/_bounds.py index da3f72a3..4036d63d 100644 --- a/src/frequenz/client/common/metrics/_bounds.py +++ b/src/frequenz/client/common/metrics/_bounds.py @@ -19,8 +19,9 @@ class BaseBounds: """A base class for well-formed and malformed metric bounds. - This class cannot be instantiated directly. Use [`Bounds`][..Bounds] for a - valid pair of bounds or [`InvalidBounds`][..InvalidBounds] to preserve + This class cannot be instantiated directly. Use + [`Bounds`][frequenz.client.common.metrics.Bounds] for a valid pair of bounds or + [`InvalidBounds`][frequenz.client.common.metrics.InvalidBounds] to preserve malformed wire data. """ @@ -57,11 +58,12 @@ class Bounds(BaseBounds): `Bounds(lower=-math.inf, upper=math.inf)` is exactly `Bounds()`. Note: - Raises a `ValueError` if [`lower`][.lower] is greater than - [`upper`][.upper], or if either bound is `NaN` (which is never a - valid endpoint). A wrong-side infinity (`+inf` lower or `-inf` - upper) is kept as a real endpoint, so a contradictory pair still - raises. Use [`InvalidBounds`][..InvalidBounds] to represent + Raises a `ValueError` if [`lower`][frequenz.client.common.metrics.Bounds.lower] + is greater than [`upper`][frequenz.client.common.metrics.Bounds.upper], or if + either bound is `NaN` (which is never a valid endpoint). A wrong-side infinity + (`+inf` lower or `-inf` upper) is kept as a real endpoint, so a contradictory + pair still raises. Use + [`InvalidBounds`][frequenz.client.common.metrics.InvalidBounds] to represent malformed bounds data received from the wire. """ @@ -149,10 +151,10 @@ def is_bounded(self) -> bool: class InvalidBounds(BaseBounds): """Metric bounds with malformed data received from the wire. - This class preserves bounds data that fails the invariants required for - a well-formed [`Bounds`][..Bounds], allowing callers to inspect the raw - values without accidentally using them for range checks. Use a semantic - accessor, such as `ElectricalComponent.get_metric_config_bounds()`, to + This class preserves bounds data that fails the invariants required for a + well-formed [`Bounds`][frequenz.client.common.metrics.Bounds], allowing callers to + inspect the raw values without accidentally using them for range checks. Use a + semantic accessor, such as `ElectricalComponent.get_metric_config_bounds()`, to receive a clear error on invalid data. """ @@ -164,8 +166,10 @@ def __str__(self) -> str: class InvalidBoundsError(InvalidAttributeError): """Raised when a semantic accessor sees invalid metric bounds. - The offending [`InvalidBounds`][..InvalidBounds] is available as the - [`bounds`][.bounds] attribute so callers can inspect the raw wire data. + The offending [`InvalidBounds`][frequenz.client.common.metrics.InvalidBounds] is + available as the + [`bounds`][frequenz.client.common.metrics.InvalidBoundsError.bounds] attribute so + callers can inspect the raw wire data. This is also a [`ValueError`][] for convenience. """ @@ -289,12 +293,11 @@ class BoundsSet: """A normalized set of metric bounds for efficient membership testing. A `BoundsSet` represents the union of a collection of - [`Bounds`][..Bounds]: a value is contained when it falls within *any* of - them. This matches the way multiple metric-sample bounds work — the value - must be within at least one of the bounds. On construction the bounds are - sorted by their lower bound and any overlapping or touching bounds are - merged, so the stored `bounds` are canonical: sorted and pairwise - non-overlapping. + [`Bounds`][frequenz.client.common.metrics.Bounds]: a value is contained when it + falls within *any* of them. This matches the way multiple metric-sample bounds work + — the value must be within at least one of the bounds. On construction the bounds + are sorted by their lower bound and any overlapping or touching bounds are merged, + so the stored `bounds` are canonical: sorted and pairwise non-overlapping. Note: This is a domain-specialized set, not a mathematical one: **the empty @@ -394,17 +397,18 @@ def __str__(self) -> str: class InvalidBoundsSet: """A set of metric bounds built from at least one malformed bound. - When a collection of bounds contains any [`InvalidBounds`][..InvalidBounds] - it cannot be normalized into a well-formed [`BoundsSet`][..BoundsSet]: - malformed ranges cannot be meaningfully sorted or merged. This type - preserves all of the raw bounds — valid and invalid alike — in their - original order, so callers can inspect exactly what was received without - accidentally range-checking against broken data. - - Unlike [`BoundsSet`][..BoundsSet], this type intentionally provides no - membership test: malformed bounds must not be used for range checks. Use a - semantic accessor, such as `MetricSample.get_bounds_set()`, to receive a - clear error on invalid data. + When a collection of bounds contains any + [`InvalidBounds`][frequenz.client.common.metrics.InvalidBounds] it cannot be + normalized into a well-formed + [`BoundsSet`][frequenz.client.common.metrics.BoundsSet]: malformed ranges cannot be + meaningfully sorted or merged. This type preserves all of the raw bounds — valid and + invalid alike — in their original order, so callers can inspect exactly what was + received without accidentally range-checking against broken data. + + Unlike [`BoundsSet`][frequenz.client.common.metrics.BoundsSet], this type + intentionally provides no membership test: malformed bounds must not be used for + range checks. Use a semantic accessor, such as `MetricSample.get_bounds_set()`, to + receive a clear error on invalid data. """ bounds: tuple[Bounds | InvalidBounds, ...] = () @@ -419,9 +423,10 @@ def __str__(self) -> str: class InvalidBoundsSetError(InvalidAttributeError): """Raised when a semantic accessor sees an invalid bounds set. - The offending [`InvalidBoundsSet`][..InvalidBoundsSet] is available as the - [`bounds_set`][.bounds_set] attribute so callers can inspect the raw wire - data. + The offending [`InvalidBoundsSet`][frequenz.client.common.metrics.InvalidBoundsSet] + is available as the + [`bounds_set`][frequenz.client.common.metrics.InvalidBoundsSetError.bounds_set] + attribute so callers can inspect the raw wire data. This is also a [`ValueError`][] for convenience. """ diff --git a/src/frequenz/client/common/metrics/_sample.py b/src/frequenz/client/common/metrics/_sample.py index ea80c836..da9d57a0 100644 --- a/src/frequenz/client/common/metrics/_sample.py +++ b/src/frequenz/client/common/metrics/_sample.py @@ -121,10 +121,10 @@ class MetricConnection: name: str = "" """The name of the specific connection from which the metric was obtained. - This is expected to be populated when the same [`Metric`][...Metric] variant - can be obtained from multiple distinct inputs or connection points on the - component. Knowing the connection for the metric can help in certain control - and monitoring applications. + This is expected to be populated when the same + [`Metric`][frequenz.client.common.metrics.Metric] variant can be obtained from + multiple distinct inputs or connection points on the component. Knowing the + connection for the metric can help in certain control and monitoring applications. """ def __str__(self) -> str: @@ -191,17 +191,19 @@ class MetricSample: """The moment when the metric was sampled. A [`datetime`][datetime.datetime] for a well-formed wire timestamp, or an - [`InvalidDatetime`][....InvalidDatetime] preserving the raw seconds and - nanoseconds when the wire carried a malformed one. + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime] preserving the raw + seconds and nanoseconds when the wire carried a malformed one. Tip: - Prefer [`get_sample_time()`][..get_sample_time] to obtain a valid - [`datetime`][datetime.datetime] or a clear error. + Prefer + [`get_sample_time()`][frequenz.client.common.metrics.MetricSample.get_sample_time] + to obtain a valid [`datetime`][datetime.datetime] or a clear error. Note: - This field replaces the deprecated [`sample_time`][..sample_time] - property, which cannot express the malformed case. It will be renamed - back to `sample_time` once that property is removed. + This field replaces the deprecated + [`sample_time`][frequenz.client.common.metrics.MetricSample.sample_time] + property, which cannot express the malformed case. It will be renamed back to + `sample_time` once that property is removed. """ metric: Metric | int @@ -221,12 +223,14 @@ class MetricSample: These bounds adapt in real-time to reflect the operating conditions at the time of aggregation or derivation. They form a union: the value of the metric must be within - at least one of them, and an empty [`BoundsSet`][...BoundsSet] means the metric is + at least one of them, and an empty + [`BoundsSet`][frequenz.client.common.metrics.BoundsSet] means the metric is unbounded. - This is a [`BoundsSet`][...BoundsSet] for well-formed data, or an - [`InvalidBoundsSet`][...InvalidBoundsSet] preserving the raw bounds when the wire - carried any malformed entry, so callers must handle both. + This is a [`BoundsSet`][frequenz.client.common.metrics.BoundsSet] for well-formed + data, or an [`InvalidBoundsSet`][frequenz.client.common.metrics.InvalidBoundsSet] + preserving the raw bounds when the wire carried any malformed entry, so callers must + handle both. Tip: Prefer `MetricSample.get_bounds_set()` to obtain a valid `BoundsSet` or a @@ -241,9 +245,9 @@ class MetricSample: connection: MetricConnection | None = None """The specific source or connection from which the metric was sampled. - This will be present when the same [`Metric`][...Metric] can be obtained from - multiple sources or connections. Knowing the connection can help in certain - control and monitoring applications. + This will be present when the same [`Metric`][frequenz.client.common.metrics.Metric] + can be obtained from multiple sources or connections. Knowing the connection can + help in certain control and monitoring applications. In cases where the component has just one connection for a metric, then the connection is `None`. @@ -274,20 +278,21 @@ def __init__( # noqa: DOC502 """Initialize this metric sample. Args: - sample_time: The moment when the metric was sampled, as a - well-formed [`datetime`][datetime.datetime]. This spelling - stays valid: it will accept the wider type once - [`sample_time2`][..sample_time2] is renamed back to - `sample_time`. - sample_time2: The moment when the metric was sampled, which may be - an [`InvalidDatetime`][....InvalidDatetime]. Use this to build - a sample from a malformed wire timestamp. + sample_time: The moment when the metric was sampled, as a well-formed + [`datetime`][datetime.datetime]. This spelling stays valid: it will + accept the wider type once + [`sample_time2`][frequenz.client.common.metrics.MetricSample.sample_time2] + is renamed back to `sample_time`. + sample_time2: The moment when the metric was sampled, which may be an + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime]. Use this to + build a sample from a malformed wire timestamp. metric: The metric that was sampled. value: The value of the sampled metric. bounds_set: The bounds that apply to the metric sample. bounds: Deprecated alias that accepts a list of valid - [`Bounds`][...Bounds] and stores them as a - [`BoundsSet`][...BoundsSet]. Use `bounds_set` instead. + [`Bounds`][frequenz.client.common.metrics.Bounds] and stores them as a + [`BoundsSet`][frequenz.client.common.metrics.BoundsSet]. Use + `bounds_set` instead. connection: The source or connection the metric was sampled from. Raises: @@ -386,10 +391,12 @@ def sample_time(self) -> datetime: # noqa: DOC502 """The moment when the metric was sampled. Warning: Deprecated - Use [`sample_time2`][..sample_time2] instead, or - [`get_sample_time()`][..get_sample_time] when a valid - [`datetime`][datetime.datetime] is required. This property keeps - the released `datetime` type, so it cannot express a malformed wire + Use + [`sample_time2`][frequenz.client.common.metrics.MetricSample.sample_time2] + instead, or + [`get_sample_time()`][frequenz.client.common.metrics.MetricSample.get_sample_time] + when a valid [`datetime`][datetime.datetime] is required. This property + keeps the released `datetime` type, so it cannot express a malformed wire timestamp and raises for one instead. Returns: @@ -398,8 +405,8 @@ def sample_time(self) -> datetime: # noqa: DOC502 Raises: InvalidDatetimeError: If the sample time is an - [`InvalidDatetime`][....InvalidDatetime]. The offending - instance is available on the error's `datetime` attribute. + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime]. The + offending instance is available on the error's `datetime` attribute. """ return self.get_sample_time() @@ -409,11 +416,10 @@ def bounds(self) -> list[Bounds]: """The valid bounds that apply to the metric sample. Warning: Deprecated - Use `bounds_set` instead. For backward compatibility this returns - only the valid [`Bounds`][...Bounds] from `bounds_set` (dropping any - malformed entries, as the old field did), but it returns the - normalized, merged bounds rather than the raw list received on the - wire. + Use `bounds_set` instead. For backward compatibility this returns only the + valid [`Bounds`][frequenz.client.common.metrics.Bounds] from `bounds_set` + (dropping any malformed entries, as the old field did), but it returns the + normalized, merged bounds rather than the raw list received on the wire. Returns: The valid bounds in `bounds_set`. @@ -428,13 +434,14 @@ def as_single_value( ) -> FloatInt | None: """Return the value of this sample as a single value. - If [`value`][..value] is a number, it is returned as is. If `value` - is an [`AggregatedMetricValue`][...AggregatedMetricValue], the value is - aggregated using the provided `aggregation_method`. + If [`value`][frequenz.client.common.metrics.MetricSample.value] is a number, it + is returned as is. If `value` is an + [`AggregatedMetricValue`][frequenz.client.common.metrics.AggregatedMetricValue], + the value is aggregated using the provided `aggregation_method`. Args: - aggregation_method: The method to use to aggregate the value when `value` - is an [`AggregatedMetricValue`][...AggregatedMetricValue]. + aggregation_method: The method used to aggregate the value when it is an + [`AggregatedMetricValue`][frequenz.client.common.metrics.AggregatedMetricValue]. Returns: The value of the sample as a single value, or `None` if the value is `None`. @@ -462,16 +469,16 @@ def get_sample_time(self) -> datetime: This is the higher-level accessor for the lower-level [`sample_time2`][frequenz.client.common.metrics.MetricSample.sample_time2] - field: it returns a valid [`datetime`][datetime.datetime] or raises - instead of exposing an [`InvalidDatetime`][....InvalidDatetime]. + field: it returns a valid [`datetime`][datetime.datetime] or raises instead of + exposing an [`InvalidDatetime`][frequenz.client.common.InvalidDatetime]. Returns: The sample time when it is a valid [`datetime`][datetime.datetime]. Raises: InvalidDatetimeError: If the sample time is an - [`InvalidDatetime`][....InvalidDatetime]. The offending - instance is available on the error's `datetime` attribute. + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime]. The + offending instance is available on the error's `datetime` attribute. """ match self.sample_time2: case datetime() as sample_time: diff --git a/src/frequenz/client/common/metrics/proto/v1alpha8/_bounds.py b/src/frequenz/client/common/metrics/proto/v1alpha8/_bounds.py index 33368eb4..00f185ca 100644 --- a/src/frequenz/client/common/metrics/proto/v1alpha8/_bounds.py +++ b/src/frequenz/client/common/metrics/proto/v1alpha8/_bounds.py @@ -17,19 +17,20 @@ "`bounds_from_proto2` (returns `Bounds | InvalidBounds`) instead." ) def bounds_from_proto(message: bounds_pb2.Bounds) -> Bounds: # noqa: DOC502 - """Create a [`Bounds`][....Bounds] object from a protobuf message. + """Create a bounds object from a protobuf message. Warning: Deprecated - Use [`bounds_from_proto2`][..bounds_from_proto2] instead. The new - converter distinguishes well-formed from malformed data at the - type level (`Bounds | InvalidBounds`) rather than raising a - `ValueError` when the invariant fires. + Use + [`bounds_from_proto2`][frequenz.client.common.metrics.proto.v1alpha8.bounds_from_proto2] + instead. The new converter distinguishes well-formed from malformed data at the + type level (`Bounds | InvalidBounds`) rather than raising a `ValueError` when + the invariant fires. Args: message: The protobuf message to convert. Returns: - The corresponding [`Bounds`][....Bounds] object. + The corresponding [`Bounds`][frequenz.client.common.metrics.Bounds] object. Raises: ValueError: If the message is not valid. @@ -49,10 +50,10 @@ def bounds_from_proto2( message: The protobuf message to convert. Returns: - A [`Bounds`][....Bounds] when the values form a valid range, or an - [`InvalidBounds`][....InvalidBounds] preserving values that - violate `lower <= upper`. A present but empty protobuf message - becomes an unbounded `Bounds()`. + A [`Bounds`][frequenz.client.common.metrics.Bounds] when the values form a valid + range, or an [`InvalidBounds`][frequenz.client.common.metrics.InvalidBounds] + preserving values that violate `lower <= upper`. A present but empty + protobuf message becomes an unbounded `Bounds()`. """ lower = message.lower if message.HasField("lower") else None upper = message.upper if message.HasField("upper") else None @@ -69,17 +70,17 @@ def bounds_set_from_proto( """Convert a sequence of bounds messages into a single bounds set. This is the multi-bound counterpart of - [`bounds_from_proto2`][..bounds_from_proto2]: it converts each message and - combines the results. + [`bounds_from_proto2`][frequenz.client.common.metrics.proto.v1alpha8.bounds_from_proto2]: + it converts each message and combines the results. Args: messages: The bounds messages to convert. Returns: - A [`BoundsSet`][....BoundsSet] (the union of the bounds) when every - message is well-formed, or an - [`InvalidBoundsSet`][....InvalidBoundsSet] preserving all the raw - bounds in order when any message is malformed. + A [`BoundsSet`][frequenz.client.common.metrics.BoundsSet] (the union of the + bounds) when every message is well-formed, or an + [`InvalidBoundsSet`][frequenz.client.common.metrics.InvalidBoundsSet] + preserving all the raw bounds in order when any message is malformed. """ valid: list[Bounds] = [] raw: list[Bounds | InvalidBounds] = [] @@ -111,14 +112,14 @@ def bounds_from_proto_with_issues( major_issues: list[str], minor_issues: list[str], # pylint: disable=unused-argument ) -> Bounds | None: # noqa: DOC502 - """Create a [`Bounds`][....Bounds] object from a protobuf message, collecting issues. + """Create a bounds object from a protobuf message, collecting issues. Warning: Deprecated - Use [`bounds_from_proto2`][..bounds_from_proto2] instead and - inspect the returned type. The new converter distinguishes - well-formed from malformed data at the type level - (`Bounds | InvalidBounds`) rather than routing invalid data - through a side-channel string list. + Use + [`bounds_from_proto2`][frequenz.client.common.metrics.proto.v1alpha8.bounds_from_proto2] + instead and inspect the returned type. The new converter distinguishes + well-formed from malformed data at the type level (`Bounds | InvalidBounds`) + rather than routing invalid data through a side-channel string list. Args: message: The protobuf message to convert. @@ -126,7 +127,7 @@ def bounds_from_proto_with_issues( minor_issues: A list to append minor issues to. Returns: - The corresponding [`Bounds`][....Bounds] object. + The corresponding [`Bounds`][frequenz.client.common.metrics.Bounds] object. """ try: return Bounds( diff --git a/src/frequenz/client/common/metrics/proto/v1alpha8/_metric.py b/src/frequenz/client/common/metrics/proto/v1alpha8/_metric.py index 9f282b55..d0c9bbe4 100644 --- a/src/frequenz/client/common/metrics/proto/v1alpha8/_metric.py +++ b/src/frequenz/client/common/metrics/proto/v1alpha8/_metric.py @@ -10,23 +10,24 @@ def metric_from_proto(message: metrics_pb2.Metric.ValueType) -> Metric | int: - """Convert a protobuf `Metric` message to a [`Metric`][....Metric] enum member. + """Convert a protobuf `Metric` message to an enum member. Args: message: The protobuf message to convert. Returns: - The corresponding [`Metric`][....Metric] enum member, or the raw [`int`][] - if the protobuf value is not recognized. + The corresponding [`Metric`][frequenz.client.common.metrics.Metric] enum member, + or the raw [`int`][] if the protobuf value is not recognized. """ return enum_from_proto(message, Metric) def metric_to_proto(metric: Metric) -> metrics_pb2.Metric.ValueType: - """Convert a [`Metric`][....Metric] enum member to a protobuf `Metric` value. + """Convert an enum member to a protobuf `Metric` value. Args: - metric: The enum member to convert. + metric: The [`Metric`][frequenz.client.common.metrics.Metric] enum member to + convert. Returns: The corresponding protobuf `Metric` value. diff --git a/src/frequenz/client/common/metrics/proto/v1alpha8/_metric_connection_category.py b/src/frequenz/client/common/metrics/proto/v1alpha8/_metric_connection_category.py index 23a7935d..fbb1cac1 100644 --- a/src/frequenz/client/common/metrics/proto/v1alpha8/_metric_connection_category.py +++ b/src/frequenz/client/common/metrics/proto/v1alpha8/_metric_connection_category.py @@ -19,8 +19,8 @@ def metric_connection_category_from_proto( Returns: The corresponding - [`MetricConnectionCategory`][....MetricConnectionCategory] enum - member, or the raw [`int`][] if the protobuf value is not recognized. + [`MetricConnectionCategory`][frequenz.client.common.metrics.MetricConnectionCategory] + enum member, or the raw [`int`][] if the protobuf value is not recognized. """ return enum_from_proto(message, MetricConnectionCategory) @@ -31,7 +31,8 @@ def metric_connection_category_to_proto( """Convert a `MetricConnectionCategory` enum member to a protobuf value. Args: - category: The [`MetricConnectionCategory`][....MetricConnectionCategory] + category: The + [`MetricConnectionCategory`][frequenz.client.common.metrics.MetricConnectionCategory] enum member to convert. Returns: diff --git a/src/frequenz/client/common/metrics/proto/v1alpha8/_sample.py b/src/frequenz/client/common/metrics/proto/v1alpha8/_sample.py index c2abadad..985d8166 100644 --- a/src/frequenz/client/common/metrics/proto/v1alpha8/_sample.py +++ b/src/frequenz/client/common/metrics/proto/v1alpha8/_sample.py @@ -25,13 +25,15 @@ def aggregated_metric_sample_from_proto( message: metrics_pb2.AggregatedMetricValue, ) -> AggregatedMetricValue: - """Convert a protobuf message to an [`AggregatedMetricValue`][....AggregatedMetricValue] object. + """Convert a protobuf message to an aggregated metric value object. Args: message: The protobuf message to convert. Returns: - The resulting [`AggregatedMetricValue`][....AggregatedMetricValue] object. + The resulting + [`AggregatedMetricValue`][frequenz.client.common.metrics.AggregatedMetricValue] + object. """ return AggregatedMetricValue( avg=message.avg_value, @@ -44,7 +46,7 @@ def aggregated_metric_sample_from_proto( def metric_connection_from_proto( message: metrics_pb2.MetricConnection, ) -> MetricConnection: - """Convert a protobuf message to a [`MetricConnection`][....MetricConnection] object. + """Convert a protobuf message to a metric connection object. An unspecified category is preserved as the raw integer `0` and an unrecognized one as its raw integer value in the `category` field (typed @@ -55,7 +57,9 @@ def metric_connection_from_proto( message: The protobuf message to convert. Returns: - The resulting [`MetricConnection`][....MetricConnection] object. + The resulting + [`MetricConnection`][frequenz.client.common.metrics.MetricConnection] + object. """ raw = message.category category: MetricConnectionCategory | int = ( @@ -71,7 +75,7 @@ def metric_connection_from_proto( def metric_sample_from_proto( message: metrics_pb2.MetricSample, ) -> MetricSample: - """Convert a protobuf message to a [`MetricSample`][....MetricSample] object. + """Convert a protobuf message to a metric sample object. Malformed or forward-incompatible input is surfaced through the returned type rather than a side channel: an unspecified metric is preserved as the @@ -84,7 +88,8 @@ def metric_sample_from_proto( message: The protobuf message to convert. Returns: - The resulting [`MetricSample`][....MetricSample] object. + The resulting [`MetricSample`][frequenz.client.common.metrics.MetricSample] + object. """ sample_time = datetime_from_proto2(message.sample_time) @@ -131,14 +136,15 @@ def metric_connection_from_proto_with_issues( major_issues: list[str], minor_issues: list[str], ) -> MetricConnection: - """Convert a protobuf message to a [`MetricConnection`][....MetricConnection] object. + """Convert a protobuf message to a metric connection object. Warning: Deprecated - Use [`metric_connection_from_proto`][..metric_connection_from_proto] - instead and inspect the returned type. The new converter encodes an - unspecified or unrecognized category in the returned - `MetricConnection.category` field (`MetricConnectionCategory | int`) - rather than routing it through a side-channel string list. + Use + [`metric_connection_from_proto`][frequenz.client.common.metrics.proto.v1alpha8.metric_connection_from_proto] + instead and inspect the returned type. The new converter encodes an unspecified + or unrecognized category in the returned `MetricConnection.category` field + (`MetricConnectionCategory | int`) rather than routing it through a side-channel + string list. Args: message: The protobuf message to convert. @@ -146,7 +152,9 @@ def metric_connection_from_proto_with_issues( minor_issues: A list to append minor issues to. Returns: - The resulting [`MetricConnection`][....MetricConnection] object. + The resulting + [`MetricConnection`][frequenz.client.common.metrics.MetricConnection] + object. """ raw = message.category category: MetricConnectionCategory | int = ( @@ -174,21 +182,21 @@ def metric_sample_from_proto_with_issues( major_issues: list[str], minor_issues: list[str], ) -> MetricSample: - """Convert a protobuf message to a [`MetricSample`][....MetricSample] object. + """Convert a protobuf message to a metric sample object. Warning: Deprecated - Use [`metric_sample_from_proto`][..metric_sample_from_proto] instead - and inspect the returned type. The new converter encodes an - unspecified or unrecognized `metric` (`Metric | int`), malformed - bounds (`InvalidBoundsSet`) and an unrepresentable sample time - (`InvalidDatetime`) in the returned `MetricSample` rather than - routing them through a side-channel string list. + Use + [`metric_sample_from_proto`][frequenz.client.common.metrics.proto.v1alpha8.metric_sample_from_proto] + instead and inspect the returned type. The new converter encodes an unspecified + or unrecognized `metric` (`Metric | int`), malformed bounds (`InvalidBoundsSet`) + and an unrepresentable sample time (`InvalidDatetime`) in the returned + `MetricSample` rather than routing them through a side-channel string list. Note: A malformed `sample_time` still raises `ValueError`, as it did when the conversion went through `datetime_from_proto`. Only - [`metric_sample_from_proto`][..metric_sample_from_proto] keeps it in - the returned sample. + [`metric_sample_from_proto`][frequenz.client.common.metrics.proto.v1alpha8.metric_sample_from_proto] + keeps it in the returned sample. Args: message: The protobuf message to convert. @@ -196,7 +204,8 @@ def metric_sample_from_proto_with_issues( minor_issues: A list to append minor issues to. Returns: - The resulting [`MetricSample`][....MetricSample] object. + The resulting [`MetricSample`][frequenz.client.common.metrics.MetricSample] + object. Raises: ValueError: If the sample time is not a well-formed protobuf diff --git a/src/frequenz/client/common/microgrid/_lifetime.py b/src/frequenz/client/common/microgrid/_lifetime.py index 7cc086b6..e7b4f76d 100644 --- a/src/frequenz/client/common/microgrid/_lifetime.py +++ b/src/frequenz/client/common/microgrid/_lifetime.py @@ -15,31 +15,34 @@ class Lifetime: """An active operational period of an asset. - When both [`start_time`][.start_time] and [`end_time`][.end_time] are - `None`, the lifetime is unbounded and the asset is considered operational - at every timestamp. + When both [`start_time`][frequenz.client.common.microgrid.Lifetime.start_time] and + [`end_time`][frequenz.client.common.microgrid.Lifetime.end_time] are `None`, the + lifetime is unbounded and the asset is considered operational at every timestamp. - Both timestamps are well-formed [`datetime`][datetime.datetime] values. - A lifetime built from a malformed wire timestamp is an - [`InvalidLifetime`][..InvalidLifetime] instead, so code holding a - `Lifetime` can compare and order its ends without checking them first. + Both timestamps are well-formed [`datetime`][datetime.datetime] values. A lifetime + built from a malformed wire timestamp is an + [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime] instead, so + code holding a `Lifetime` can compare and order its ends without checking them + first. Warning: - The [`end_time`][.end_time] timestamp indicates that the asset has been - permanently removed from service. + The [`end_time`][frequenz.client.common.microgrid.Lifetime.end_time] timestamp + indicates that the asset has been permanently removed from service. Note: - Raises a `ValueError` if [`start_time`][.start_time] is later than the - [`end_time`][.end_time] timestamp. Use - [`InvalidLifetime`][..InvalidLifetime] to represent malformed lifetime - data received from the wire. + Raises a `ValueError` if + [`start_time`][frequenz.client.common.microgrid.Lifetime.start_time] is later + than the [`end_time`][frequenz.client.common.microgrid.Lifetime.end_time] + timestamp. Use + [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime] to + represent malformed lifetime data received from the wire. """ start_time: datetime | None = None """The moment when the asset became operationally active. If `None`, the asset is considered to be active in any past moment previous to the - [`end_time`][..end_time]. + [`end_time`][frequenz.client.common.microgrid.Lifetime.end_time]. """ end_time: datetime | None = None @@ -52,8 +55,10 @@ def __post_init__(self) -> None: """Validate this lifetime. Raises: - ValueError: If [`start_time`][..start_time] is later than - [`end_time`][..end_time]. + ValueError: If + [`start_time`][frequenz.client.common.microgrid.Lifetime.start_time] is + later than + [`end_time`][frequenz.client.common.microgrid.Lifetime.end_time]. """ if ( self.start_time is not None @@ -94,15 +99,17 @@ def is_operational_now(self) -> bool: class InvalidLifetime: """An operational lifetime with malformed data received from the wire. - This class preserves lifetime data that fails the invariants required for - a well-formed [`Lifetime`][..Lifetime], allowing callers to inspect the raw - timestamps without accidentally using them for operational checks. Use a - semantic accessor, such as `ElectricalComponent.get_operational_lifetime()`, - to receive a clear [`InvalidLifetimeError`][..InvalidLifetimeError]. - - Either end may also be an [`InvalidDatetime`][...InvalidDatetime], for a - wire timestamp that is not a well-formed protobuf `Timestamp`. This class - enforces no invariants, so it provides no operational checks and no + This class preserves lifetime data that fails the invariants required for a + well-formed [`Lifetime`][frequenz.client.common.microgrid.Lifetime], allowing + callers to inspect the raw timestamps without accidentally using them for + operational checks. Use a semantic accessor, such as + `ElectricalComponent.get_operational_lifetime()`, to receive a clear + [`InvalidLifetimeError`][frequenz.client.common.microgrid.InvalidLifetimeError]. + + Either end may also be an + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime], for a wire timestamp + that is not a well-formed protobuf `Timestamp`. This class enforces no invariants, + so it provides no operational checks and no accessors: code that reaches an `InvalidLifetime` is already handling malformed data and reads the two fields directly. """ @@ -111,16 +118,16 @@ class InvalidLifetime: """The moment when the asset became operationally active. `None` when the wire did not set it. An - [`InvalidDatetime`][....InvalidDatetime] when the wire set a malformed - timestamp. + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime] when the wire set a + malformed timestamp. """ end_time: datetime | InvalidDatetime | None = None """The moment when the asset's operational activity ceased. `None` when the wire did not set it. An - [`InvalidDatetime`][....InvalidDatetime] when the wire set a malformed - timestamp. + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime] when the wire set a + malformed timestamp. """ def __str__(self) -> str: @@ -155,8 +162,10 @@ def _format_time(value: datetime | InvalidDatetime | None, *, unset: str) -> str class InvalidLifetimeError(InvalidAttributeError): """Raised when a semantic accessor sees an invalid lifetime. - The offending [`InvalidLifetime`][..InvalidLifetime] is available as the - [`lifetime`][.lifetime] attribute so callers can inspect the raw wire data. + The offending [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime] + is available as the + [`lifetime`][frequenz.client.common.microgrid.InvalidLifetimeError.lifetime] + attribute so callers can inspect the raw wire data. This is also a [`ValueError`][] for convenience. """ diff --git a/src/frequenz/client/common/microgrid/_microgrid.py b/src/frequenz/client/common/microgrid/_microgrid.py index f83f3ff2..75f4798b 100644 --- a/src/frequenz/client/common/microgrid/_microgrid.py +++ b/src/frequenz/client/common/microgrid/_microgrid.py @@ -53,12 +53,14 @@ class Microgrid: # pylint: disable=too-many-instance-attributes """The delivery area where the microgrid is located. `None` means the field was not set on the wire. An - [`InvalidDeliveryArea`][....grid.InvalidDeliveryArea] means the wire - carried a delivery area that fails its invariants. + [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea] means the + wire carried a delivery area that fails its invariants. Tip: - This is the lower-level field; prefer [`get_delivery_area()`][..get_delivery_area] - to obtain a valid [`DeliveryArea`][....grid.DeliveryArea] or a clear error. + This is the lower-level field; prefer + [`get_delivery_area()`][frequenz.client.common.microgrid.Microgrid.get_delivery_area] + to obtain a valid [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea] or + a clear error. """ location: Location | None @@ -67,13 +69,13 @@ class Microgrid: # pylint: disable=too-many-instance-attributes create_time: datetime.datetime | InvalidDatetime """The UTC timestamp indicating when the microgrid was initially created. - An [`InvalidDatetime`][....InvalidDatetime] preserves the raw seconds - and nanoseconds when the wire carried a timestamp Python cannot represent. + An [`InvalidDatetime`][frequenz.client.common.InvalidDatetime] preserves the raw + seconds and nanoseconds when the wire carried a timestamp Python cannot represent. Tip: This is the lower-level field; prefer - [`get_create_time()`][..get_create_time] to obtain a valid - [`datetime`][datetime.datetime] or a clear error. + [`get_create_time()`][frequenz.client.common.microgrid.Microgrid.get_create_time] + to obtain a valid [`datetime`][datetime.datetime] or a clear error. """ _active: bool | int @@ -82,7 +84,8 @@ class Microgrid: # pylint: disable=too-many-instance-attributes This stores the low-level representation of the microgrid state. It holds a `bool` for a known active/inactive status, the raw `int` `0` when the status is unspecified, or any other raw `int` not yet known to this client. Users should use - [`Microgrid.is_active()`][.is_active] to obtain a clear boolean or a clear error. + [`Microgrid.is_active()`][frequenz.client.common.microgrid.Microgrid.is_active] to + obtain a clear boolean or a clear error. """ _allow_construction: bool = field( @@ -95,7 +98,7 @@ def __post_init__(self) -> None: Raises: TypeError: If the instance was not created via the - [`microgrid_from_proto`][...proto.v1alpha8.microgrid_from_proto] + [`microgrid_from_proto`][frequenz.client.common.microgrid.proto.v1alpha8.microgrid_from_proto] converter. """ if not self._allow_construction: @@ -135,20 +138,22 @@ def is_active(self) -> bool: def get_delivery_area(self) -> DeliveryArea: """Return the delivery area as a well-formed `DeliveryArea`. - This is the higher-level accessor for the [`delivery_area`][..delivery_area] + This is the higher-level accessor for the + [`delivery_area`][frequenz.client.common.microgrid.Microgrid.delivery_area] attribute: it resolves the field to a valid - [`DeliveryArea`][....grid.DeliveryArea] or raises a clear, catchable error. + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea] or raises a clear, + catchable error. Returns: The delivery area, when it is a well-formed - [`DeliveryArea`][....grid.DeliveryArea]. + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea]. Raises: MissingFieldError: If the delivery area is not set (`None`). InvalidDeliveryAreaError: If the delivery area is an - [`InvalidDeliveryArea`][....grid.InvalidDeliveryArea]. The - offending instance is available on the exception's - `delivery_area` attribute. + [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea]. + The offending instance is available on the exception's `delivery_area` + attribute. """ match self.delivery_area: case None: @@ -163,22 +168,23 @@ def get_delivery_area(self) -> DeliveryArea: def get_delivery_area_or_none(self) -> DeliveryArea | None: """Return the delivery area as a well-formed `DeliveryArea`, or `None`. - This is the higher-level accessor for the [`delivery_area`][..delivery_area] - attribute that tolerates a missing field: it resolves the field to a - valid [`DeliveryArea`][....grid.DeliveryArea], returns `None` when the - field was not set on the wire, or raises a clear, catchable error when - the field carries an invalid delivery area. + This is the higher-level accessor for the + [`delivery_area`][frequenz.client.common.microgrid.Microgrid.delivery_area] + attribute that tolerates a missing field: it resolves the field to a valid + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea], returns `None` when + the field was not set on the wire, or raises a clear, catchable error when the + field carries an invalid delivery area. Returns: The delivery area when it is a well-formed - [`DeliveryArea`][....grid.DeliveryArea], or `None` when it is - not set. + [`DeliveryArea`][frequenz.client.common.grid.DeliveryArea], or `None` + when it is not set. Raises: InvalidDeliveryAreaError: If the delivery area is an - [`InvalidDeliveryArea`][....grid.InvalidDeliveryArea]. The - offending instance is available on the exception's - `delivery_area` attribute. + [`InvalidDeliveryArea`][frequenz.client.common.grid.InvalidDeliveryArea]. + The offending instance is available on the exception's `delivery_area` + attribute. """ match self.delivery_area: case None: @@ -193,7 +199,8 @@ def get_delivery_area_or_none(self) -> DeliveryArea | None: def get_create_time(self) -> datetime.datetime: """Return the creation time as a valid `datetime`. - This is the higher-level accessor for the [`create_time`][..create_time] + This is the higher-level accessor for the + [`create_time`][frequenz.client.common.microgrid.Microgrid.create_time] attribute: it resolves the field to a valid [`datetime`][datetime.datetime] or raises a clear, catchable error. @@ -203,9 +210,8 @@ def get_create_time(self) -> datetime.datetime: Raises: InvalidDatetimeError: If the creation time is an - [`InvalidDatetime`][....InvalidDatetime]. The offending - instance is available on the exception's `datetime` - attribute. + [`InvalidDatetime`][frequenz.client.common.InvalidDatetime]. The + offending instance is available on the exception's `datetime` attribute. """ match self.create_time: case datetime.datetime() as valid: @@ -216,15 +222,17 @@ def get_create_time(self) -> datetime.datetime: assert_never(unknown) def get_location(self) -> Location: - """Return the location as a [`Location`][....types.Location]. + """Return the location as a [`Location`][frequenz.client.common.types.Location]. - This is the higher-level accessor for the [`location`][..location] + This is the higher-level accessor for the + [`location`][frequenz.client.common.microgrid.Microgrid.location] attribute: it resolves the field to a - [`Location`][....types.Location] or raises a clear, catchable error. + [`Location`][frequenz.client.common.types.Location] or raises a clear, catchable + error. The returned instance may still carry raw wire values that fail the - [`Location`][....types.Location] field invariants; use its own - `get_*()` accessors to obtain validated coordinates and country code. + [`Location`][frequenz.client.common.types.Location] field invariants; use its + own `get_*()` accessors to obtain validated coordinates and country code. Returns: The location, when it is set. diff --git a/src/frequenz/client/common/microgrid/electrical_components/_electrical_component.py b/src/frequenz/client/common/microgrid/electrical_components/_electrical_component.py index c80ceb3f..2604eefe 100644 --- a/src/frequenz/client/common/microgrid/electrical_components/_electrical_component.py +++ b/src/frequenz/client/common/microgrid/electrical_components/_electrical_component.py @@ -43,11 +43,13 @@ class ElectricalComponent: # pylint: disable=too-many-instance-attributes ) """The operational lifetime of this electrical component. - An [`InvalidLifetime`][....InvalidLifetime] preserves malformed wire data. + An [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime] preserves + malformed wire data. Tip: - Prefer [`get_operational_lifetime()`][..get_operational_lifetime] when - a valid lifetime is required. + Prefer + [`get_operational_lifetime()`][frequenz.client.common.microgrid.electrical_components.ElectricalComponent.get_operational_lifetime] + when a valid lifetime is required. """ _provides_telemetry: bool | int @@ -57,8 +59,8 @@ class ElectricalComponent: # pylint: disable=too-many-instance-attributes for the telemetry part for a known operational mode, the raw `int` `0` when the operational mode is unspecified, or any other raw `int` not yet known to this client. Users should use - [`ElectricalComponent.provides_telemetry()`][.provides_telemetry] to obtain a clear - boolean or a clear error. + [`ElectricalComponent.provides_telemetry()`][frequenz.client.common.microgrid.electrical_components.ElectricalComponent.provides_telemetry] + to obtain a clear boolean or a clear error. """ _accepts_control: bool | int @@ -67,8 +69,8 @@ class ElectricalComponent: # pylint: disable=too-many-instance-attributes This stores the low-level representation of the operational mode. It holds a bool for a known operational mode, the raw `int` `0` when the operational mode is unspecified, or any other raw `int` not yet known to this client. Users should use - [`ElectricalComponent.accepts_control()`][.accepts_control] to obtain a clear - boolean or a clear error. + [`ElectricalComponent.accepts_control()`][frequenz.client.common.microgrid.electrical_components.ElectricalComponent.accepts_control] + to obtain a clear boolean or a clear error. """ _allow_construction: bool = dataclasses.field( @@ -92,9 +94,10 @@ class ElectricalComponent: # pylint: disable=too-many-instance-attributes limits, or limits of other devices. Each metric maps to the aggregate of all the bounds configured for it: a - [`BoundsSet`][.....metrics.BoundsSet] when every one is well-formed, or an - [`InvalidBoundsSet`][.....metrics.InvalidBoundsSet] preserving all the raw - bounds when any is malformed. + [`BoundsSet`][frequenz.client.common.metrics.BoundsSet] when every one is + well-formed, or an + [`InvalidBoundsSet`][frequenz.client.common.metrics.InvalidBoundsSet] preserving all + the raw bounds when any is malformed. If an unspecified metric is received, it is stored as the plain `int` key `0` when loading from protobuf. Metrics unknown to this client version may also appear @@ -108,21 +111,22 @@ class ElectricalComponent: # pylint: disable=too-many-instance-attributes the raw `0` used for an unspecified metric. Tip: - Prefer [`get_metric_config_bounds()`][..get_metric_config_bounds] - when a valid [`BoundsSet`][.....metrics.BoundsSet] is required. + Prefer + [`get_metric_config_bounds()`][frequenz.client.common.microgrid.electrical_components.ElectricalComponent.get_metric_config_bounds] + when a valid [`BoundsSet`][frequenz.client.common.metrics.BoundsSet] is + required. """ category_specific_info: CategorySpecificInfo | None = None """The category specific info carried by this component, if any. - This is `None` when the wire carried no category-specific info variant. - Otherwise it holds a - [`CategorySpecificInfo`][...CategorySpecificInfo] recording the variant - `kind` together with any fields that were not translated into typed - attributes on this component. The leftover fields are empty when everything - was translated, and non-empty when the category or its variant is not - recognized, or when a newer API version added fields this client version - doesn't know yet. + This is `None` when the wire carried no category-specific info variant. Otherwise it + holds a + [`CategorySpecificInfo`][frequenz.client.common.microgrid.electrical_components.CategorySpecificInfo] + recording the variant `kind` together with any fields that were not translated into + typed attributes on this component. The leftover fields are empty when everything + was translated, and non-empty when the category or its variant is not recognized, or + when a newer API version added fields this client version doesn't know yet. """ def __new__(cls, *_: Any, **__: Any) -> Self: @@ -248,7 +252,7 @@ def get_metric_config_bounds( ``` This is similar to accessing - [`metric_config_bounds`][...ElectricalComponent.metric_config_bounds] + [`metric_config_bounds`][frequenz.client.common.microgrid.electrical_components.ElectricalComponent.metric_config_bounds] directly, but avoid the special handling of invalid bounds. Args: @@ -260,8 +264,8 @@ def get_metric_config_bounds( `metric`. Returns: - The valid [`BoundsSet`][.....metrics.BoundsSet] configured for - `metric`, or `default` when there is no entry for `metric`. + The valid [`BoundsSet`][frequenz.client.common.metrics.BoundsSet] configured + for `metric`, or `default` when there is no entry for `metric`. Raises: InvalidBoundsSetError: If the bounds configured for `metric` are diff --git a/src/frequenz/client/common/microgrid/electrical_components/_electrical_component_connection.py b/src/frequenz/client/common/microgrid/electrical_components/_electrical_component_connection.py index 94b012ef..656c1782 100644 --- a/src/frequenz/client/common/microgrid/electrical_components/_electrical_component_connection.py +++ b/src/frequenz/client/common/microgrid/electrical_components/_electrical_component_connection.py @@ -15,14 +15,12 @@ class BaseElectricalComponentConnection: """A base class for all electrical component connections. - This is the common supertype of every kind of connection, both - well-formed (see - [`ElectricalComponentConnection`][..ElectricalComponentConnection]) and - problematic (see - [`ProblematicElectricalComponentConnection`][..ProblematicElectricalComponentConnection]). - It cannot be instantiated directly; use one of its concrete subclasses - instead, or obtain instances via the corresponding `*_from_proto` - converter. + This is the common supertype of every kind of connection, both well-formed (see + [`ElectricalComponentConnection`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentConnection]) + and problematic (see + [`ProblematicElectricalComponentConnection`][frequenz.client.common.microgrid.electrical_components.ProblematicElectricalComponentConnection]). + It cannot be instantiated directly; use one of its concrete subclasses instead, or + obtain instances via the corresponding `*_from_proto` converter. Note: Physical Representation This object is not about data flow but rather about the physical @@ -60,11 +58,13 @@ class BaseElectricalComponentConnection: ) """The operational lifetime of the connection. - An [`InvalidLifetime`][....InvalidLifetime] preserves malformed wire data. + An [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime] preserves + malformed wire data. Tip: - Prefer [`get_operational_lifetime()`][..get_operational_lifetime] when - a valid lifetime is required. + Prefer + [`get_operational_lifetime()`][frequenz.client.common.microgrid.electrical_components.BaseElectricalComponentConnection.get_operational_lifetime] + when a valid lifetime is required. """ # pylint: disable-next=unused-argument @@ -131,11 +131,10 @@ def __str__(self) -> str: class ElectricalComponentConnection(BaseElectricalComponentConnection): """A single electrical link between two distinct electrical components in a microgrid. - This is the well-formed case of an electrical component connection: the - source and destination are guaranteed to be different components. - Malformed cases (e.g. self-loops) are represented by dedicated - subclasses of - [`ProblematicElectricalComponentConnection`][..ProblematicElectricalComponentConnection] + This is the well-formed case of an electrical component connection: the source and + destination are guaranteed to be different components. Malformed cases (e.g. + self-loops) are represented by dedicated subclasses of + [`ProblematicElectricalComponentConnection`][frequenz.client.common.microgrid.electrical_components.ProblematicElectricalComponentConnection] instead. """ @@ -144,11 +143,11 @@ def __post_init__(self) -> None: Raises: ValueError: If - [`source_id`][...BaseElectricalComponentConnection.source_id] + [`source_id`][frequenz.client.common.microgrid.electrical_components.BaseElectricalComponentConnection.source_id] and - [`destination_id`][...BaseElectricalComponentConnection.destination_id] - are equal, since that would describe a self-loop rather than - a well-formed connection. + [`destination_id`][frequenz.client.common.microgrid.electrical_components.BaseElectricalComponentConnection.destination_id] + are equal, since that would describe a self-loop rather than a + well-formed connection. """ if self.source_id == self.destination_id: raise ValueError("Source and destination components must be different") diff --git a/src/frequenz/client/common/microgrid/electrical_components/_problematic_connection.py b/src/frequenz/client/common/microgrid/electrical_components/_problematic_connection.py index 246e513c..a47f04fe 100644 --- a/src/frequenz/client/common/microgrid/electrical_components/_problematic_connection.py +++ b/src/frequenz/client/common/microgrid/electrical_components/_problematic_connection.py @@ -16,9 +16,9 @@ class ProblematicElectricalComponentConnection(BaseElectricalComponentConnection This is the base class for connections that carry a data-integrity issue. Problematic connections are siblings of the well-formed - [`ElectricalComponentConnection`][..ElectricalComponentConnection]: both - extend - [`BaseElectricalComponentConnection`][..BaseElectricalComponentConnection]. + [`ElectricalComponentConnection`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentConnection]: + both extend + [`BaseElectricalComponentConnection`][frequenz.client.common.microgrid.electrical_components.BaseElectricalComponentConnection]. """ # pylint: disable-next=unused-argument @@ -48,11 +48,11 @@ def __post_init__(self) -> None: Raises: ValueError: If - [`source_id`][...BaseElectricalComponentConnection.source_id] + [`source_id`][frequenz.client.common.microgrid.electrical_components.BaseElectricalComponentConnection.source_id] and - [`destination_id`][...BaseElectricalComponentConnection.destination_id] - are different, since a self-referencing connection is defined - by them being the same. + [`destination_id`][frequenz.client.common.microgrid.electrical_components.BaseElectricalComponentConnection.destination_id] + are different, since a self-referencing connection is defined by them + being the same. """ if self.source_id != self.destination_id: raise ValueError( diff --git a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_category.py b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_category.py index 1abc3305..df2352b3 100644 --- a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_category.py +++ b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_category.py @@ -28,8 +28,8 @@ def electrical_component_category_from_proto( Returns: The corresponding - [`ElectricalComponentCategory`][....ElectricalComponentCategory] enum - member, or the raw [`int`][] if the protobuf value is not recognized. + [`ElectricalComponentCategory`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentCategory] + enum member, or the raw [`int`][] if the protobuf value is not recognized. """ with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) @@ -47,8 +47,8 @@ def electrical_component_category_to_proto( Args: category: The - [`ElectricalComponentCategory`][....ElectricalComponentCategory] enum - member to convert. + [`ElectricalComponentCategory`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentCategory] + enum member to convert. Returns: The corresponding protobuf `ElectricalComponentCategory` value. diff --git a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_diagnostic_code.py b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_diagnostic_code.py index f9182dfa..a13a6e5c 100644 --- a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_diagnostic_code.py +++ b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_diagnostic_code.py @@ -21,7 +21,7 @@ def electrical_component_diagnostic_code_from_proto( Returns: The corresponding - [`ElectricalComponentDiagnosticCode`][....ElectricalComponentDiagnosticCode] + [`ElectricalComponentDiagnosticCode`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentDiagnosticCode] enum member, or the raw [`int`][] if the protobuf value is not recognized. """ return enum_from_proto(message, ElectricalComponentDiagnosticCode) @@ -34,7 +34,7 @@ def electrical_component_diagnostic_code_to_proto( Args: diagnostic_code: The - [`ElectricalComponentDiagnosticCode`][....ElectricalComponentDiagnosticCode] + [`ElectricalComponentDiagnosticCode`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentDiagnosticCode] enum member to convert. Returns: diff --git a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_electrical_component.py b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_electrical_component.py index 84f06aa1..f2c2418f 100644 --- a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_electrical_component.py +++ b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_electrical_component.py @@ -585,9 +585,9 @@ def electrical_component_class_to_proto( ]: """Convert an electrical component class or instance to its protobuf identity. - Returns the `(category, subtype)` pair the protobuf wire format uses for - the given component. This is the inverse of - [`electrical_component_class_from_proto`][..electrical_component_class_from_proto] + Returns the `(category, subtype)` pair the protobuf wire format uses for the given + component. This is the inverse of + [`electrical_component_class_from_proto`][frequenz.client.common.microgrid.electrical_components.proto.v1alpha8.electrical_component_class_from_proto] for the classes and abstract bases it knows about. Conversion rules (`C` = class, `I` = instance): @@ -621,12 +621,11 @@ def electrical_component_class_to_proto( Key invariants: - * The abstract typed bases `Battery`, `EvCharger`, `Inverter` are - *distinct* from their `Unspecified*` counterparts on the wire: abstract - bases emit `subtype=None`, the `Unspecified*` classes emit - `subtype=<...TYPE_UNSPECIFIED>` (the concrete protobuf 0 value). This - mirrors how - [`electrical_component_class_from_proto`][..electrical_component_class_from_proto] + * The abstract typed bases `Battery`, `EvCharger`, `Inverter` are *distinct* from + their `Unspecified*` counterparts on the wire: abstract bases emit `subtype=None`, + the `Unspecified*` classes emit `subtype=<...TYPE_UNSPECIFIED>` (the concrete + protobuf 0 value). This mirrors how + [`electrical_component_class_from_proto`][frequenz.client.common.microgrid.electrical_components.proto.v1alpha8.electrical_component_class_from_proto] reads them back. * `Unrecognized*` and `MismatchedCategoryElectricalComponent` are only meaningful as **instances** because the raw, possibly out-of-range @@ -713,10 +712,10 @@ def electrical_component_class_from_proto( """Convert a protobuf `(category, subtype)` pair to an electrical component class. This is the inverse of - [`electrical_component_class_to_proto`][..electrical_component_class_to_proto]: - every input it can produce round-trips back to the matching class here. - Returns the class only — never an instance — because the protobuf identity - pair does not carry the rest of the component state. + [`electrical_component_class_to_proto`][frequenz.client.common.microgrid.electrical_components.proto.v1alpha8.electrical_component_class_to_proto]: + every input it can produce round-trips back to the matching class here. Returns the + class only — never an instance — because the protobuf identity pair does not carry + the rest of the component state. Conversion rules: diff --git a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_state_code.py b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_state_code.py index 7aed88b7..522f8539 100644 --- a/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_state_code.py +++ b/src/frequenz/client/common/microgrid/electrical_components/proto/v1alpha8/_state_code.py @@ -21,8 +21,8 @@ def electrical_component_state_code_from_proto( Returns: The corresponding - [`ElectricalComponentStateCode`][....ElectricalComponentStateCode] enum - member, or the raw [`int`][] if the protobuf value is not recognized. + [`ElectricalComponentStateCode`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentStateCode] + enum member, or the raw [`int`][] if the protobuf value is not recognized. """ return enum_from_proto(message, ElectricalComponentStateCode) @@ -34,8 +34,8 @@ def electrical_component_state_code_to_proto( Args: state_code: The - [`ElectricalComponentStateCode`][....ElectricalComponentStateCode] enum - member to convert. + [`ElectricalComponentStateCode`][frequenz.client.common.microgrid.electrical_components.ElectricalComponentStateCode] + enum member to convert. Returns: The corresponding protobuf `ElectricalComponentStateCode` value. diff --git a/src/frequenz/client/common/microgrid/proto/v1alpha8/_lifetime.py b/src/frequenz/client/common/microgrid/proto/v1alpha8/_lifetime.py index 3e3e7fae..e365d710 100644 --- a/src/frequenz/client/common/microgrid/proto/v1alpha8/_lifetime.py +++ b/src/frequenz/client/common/microgrid/proto/v1alpha8/_lifetime.py @@ -17,11 +17,11 @@ def lifetime_from_proto(message: lifetime_pb2.Lifetime) -> Lifetime | InvalidLif message: The protobuf message to convert. Returns: - A [`Lifetime`][....Lifetime] when both timestamps are well-formed and - form a valid range, or an - [`InvalidLifetime`][....InvalidLifetime] preserving a malformed - timestamp or a reversed range. A present but empty protobuf - message becomes an unbounded `Lifetime()`. + A [`Lifetime`][frequenz.client.common.microgrid.Lifetime] when both timestamps + are well-formed and form a valid range, or an + [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime] + preserving a malformed timestamp or a reversed range. A present but empty + protobuf message becomes an unbounded `Lifetime()`. """ start = ( datetime_from_proto2(message.start_timestamp) diff --git a/src/frequenz/client/common/microgrid/proto/v1alpha8/_microgrid.py b/src/frequenz/client/common/microgrid/proto/v1alpha8/_microgrid.py index 38bd8361..f2624633 100644 --- a/src/frequenz/client/common/microgrid/proto/v1alpha8/_microgrid.py +++ b/src/frequenz/client/common/microgrid/proto/v1alpha8/_microgrid.py @@ -36,7 +36,7 @@ def _microgrid_status_to_active(value: int) -> bool | int: def microgrid_from_proto(message: microgrid_pb2.Microgrid) -> Microgrid: - """Convert a protobuf message to a [`Microgrid`][....Microgrid] object. + """Convert a protobuf message to a microgrid object. Malformed input is surfaced through the returned object rather than a side channel: a malformed delivery area becomes an `InvalidDeliveryArea` and a @@ -46,7 +46,8 @@ def microgrid_from_proto(message: microgrid_pb2.Microgrid) -> Microgrid: message: The protobuf message to convert. Returns: - The corresponding [`Microgrid`][....Microgrid] object. + The corresponding [`Microgrid`][frequenz.client.common.microgrid.Microgrid] + object. """ delivery_area: DeliveryArea | InvalidDeliveryArea | None = None if message.HasField("delivery_area"): diff --git a/src/frequenz/client/common/microgrid/sensors/_sensor.py b/src/frequenz/client/common/microgrid/sensors/_sensor.py index 691c5136..ca1c0d92 100644 --- a/src/frequenz/client/common/microgrid/sensors/_sensor.py +++ b/src/frequenz/client/common/microgrid/sensors/_sensor.py @@ -41,11 +41,13 @@ class Sensor: operational_lifetime: Lifetime | InvalidLifetime = field(default_factory=Lifetime) """The operational lifetime of the sensor. - An [`InvalidLifetime`][....InvalidLifetime] preserves malformed wire data. + An [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime] preserves + malformed wire data. Tip: - Prefer [`get_operational_lifetime()`][..get_operational_lifetime] when - a valid lifetime is required. + Prefer + [`get_operational_lifetime()`][frequenz.client.common.microgrid.sensors.Sensor.get_operational_lifetime] + when a valid lifetime is required. """ _allow_construction: bool = field( @@ -58,7 +60,7 @@ def __post_init__(self) -> None: Raises: TypeError: If the instance was not created via the - [`sensor_from_proto`][...proto.v1alpha8.sensor_from_proto] + [`sensor_from_proto`][frequenz.client.common.microgrid.sensors.proto.v1alpha8.sensor_from_proto] converter. """ if not self._allow_construction: diff --git a/src/frequenz/client/common/microgrid/sensors/proto/v1alpha8/_sensor.py b/src/frequenz/client/common/microgrid/sensors/proto/v1alpha8/_sensor.py index 3e8af4de..6a1d91f7 100644 --- a/src/frequenz/client/common/microgrid/sensors/proto/v1alpha8/_sensor.py +++ b/src/frequenz/client/common/microgrid/sensors/proto/v1alpha8/_sensor.py @@ -13,18 +13,20 @@ def sensor_from_proto(message: sensors_pb2.Sensor) -> Sensor: - """Convert a protobuf message to a [`Sensor`][....Sensor] object. + """Convert a protobuf message to a sensor object. Malformed input is surfaced through the returned object rather than a side channel: a malformed operational lifetime becomes an - [`InvalidLifetime`][.....InvalidLifetime]. A missing operational lifetime - becomes an unbounded [`Lifetime`][.....Lifetime]. + [`InvalidLifetime`][frequenz.client.common.microgrid.InvalidLifetime]. A missing + operational lifetime becomes an unbounded + [`Lifetime`][frequenz.client.common.microgrid.Lifetime]. Args: message: The protobuf message to convert. Returns: - The corresponding [`Sensor`][....Sensor] object. + The corresponding [`Sensor`][frequenz.client.common.microgrid.sensors.Sensor] + object. """ operational_lifetime: Lifetime | InvalidLifetime = Lifetime() if message.HasField("operational_lifetime"): diff --git a/src/frequenz/client/common/pagination/_pagination_info.py b/src/frequenz/client/common/pagination/_pagination_info.py index eadfab57..f3fcec65 100644 --- a/src/frequenz/client/common/pagination/_pagination_info.py +++ b/src/frequenz/client/common/pagination/_pagination_info.py @@ -12,9 +12,10 @@ class BasePaginationInfo: """A base class for well-formed and malformed pagination information. This class cannot be instantiated directly. Use - [`PaginationInfo`][..PaginationInfo] for well-formed pagination - information or [`InvalidPaginationInfo`][..InvalidPaginationInfo] to - preserve malformed wire data. + [`PaginationInfo`][frequenz.client.common.pagination.PaginationInfo] for well-formed + pagination information or + [`InvalidPaginationInfo`][frequenz.client.common.pagination.InvalidPaginationInfo] + to preserve malformed wire data. """ total_items: int @@ -38,24 +39,28 @@ def __new__(cls, *args: Any, **kwargs: Any) -> Self: class PaginationInfo(BasePaginationInfo): """Information about the pagination of a list request. - The [`total_items`][.total_items] count is a number of items, so it can - never be negative. Pagination information built from a wire message that - breaks this rule is an - [`InvalidPaginationInfo`][..InvalidPaginationInfo] instead, so code - holding a `PaginationInfo` can use the count in arithmetic without + The [`total_items`][frequenz.client.common.pagination.PaginationInfo.total_items] + count is a number of items, so it can never be negative. Pagination information + built from a wire message that breaks this rule is an + [`InvalidPaginationInfo`][frequenz.client.common.pagination.InvalidPaginationInfo] + instead, so code holding a `PaginationInfo` can use the count in arithmetic without checking it first. Note: - Raises a `ValueError` if [`total_items`][.total_items] is negative. - Use [`InvalidPaginationInfo`][..InvalidPaginationInfo] to represent - malformed pagination data received from the wire. + Raises a `ValueError` if + [`total_items`][frequenz.client.common.pagination.PaginationInfo.total_items] is + negative. Use + [`InvalidPaginationInfo`][frequenz.client.common.pagination.InvalidPaginationInfo] + to represent malformed pagination data received from the wire. """ def __post_init__(self) -> None: """Validate pagination information. Raises: - ValueError: If [`total_items`][..total_items] is negative. + ValueError: If + [`total_items`][frequenz.client.common.pagination.PaginationInfo.total_items] + is negative. """ if self.total_items < 0: raise ValueError( @@ -71,9 +76,10 @@ def __str__(self) -> str: class InvalidPaginationInfo(BasePaginationInfo): """Pagination information with malformed data received from the wire. - This class preserves pagination data that fails the invariants required - for a well-formed [`PaginationInfo`][..PaginationInfo], allowing callers - to inspect the raw values without accidentally using them as a count. + This class preserves pagination data that fails the invariants required for a + well-formed [`PaginationInfo`][frequenz.client.common.pagination.PaginationInfo], + allowing callers to inspect the raw values without accidentally using them as a + count. This class does not enforce any invariants on construction. """ diff --git a/src/frequenz/client/common/pagination/proto/v1alpha8/_pagination_info.py b/src/frequenz/client/common/pagination/proto/v1alpha8/_pagination_info.py index f510b2ec..604aaafa 100644 --- a/src/frequenz/client/common/pagination/proto/v1alpha8/_pagination_info.py +++ b/src/frequenz/client/common/pagination/proto/v1alpha8/_pagination_info.py @@ -20,19 +20,21 @@ def pagination_info_from_proto( # noqa: DOC502 message: PaginationInfoPb, ) -> PaginationInfo: - """Convert a protobuf message to a [`PaginationInfo`][....PaginationInfo] object. + """Convert a protobuf message to a pagination info object. Warning: Deprecated - Use [`pagination_info_from_proto2`][..pagination_info_from_proto2] - instead. The new converter distinguishes well-formed from malformed - data at the type level (`PaginationInfo | InvalidPaginationInfo`) - rather than raising a `ValueError` when the invariant fires. + Use + [`pagination_info_from_proto2`][frequenz.client.common.pagination.proto.v1alpha8.pagination_info_from_proto2] + instead. The new converter distinguishes well-formed from malformed data at the + type level (`PaginationInfo | InvalidPaginationInfo`) rather than raising a + `ValueError` when the invariant fires. Args: message: The protobuf message to convert. Returns: - The corresponding [`PaginationInfo`][....PaginationInfo] object. + The corresponding + [`PaginationInfo`][frequenz.client.common.pagination.PaginationInfo] object. Raises: ValueError: If the message carries a negative `total_items`. @@ -48,20 +50,20 @@ def pagination_info_from_proto2( ) -> PaginationInfo | InvalidPaginationInfo: """Convert a protobuf message to pagination information, preserving malformed data. - Unlike [`pagination_info_from_proto`][..pagination_info_from_proto], the - token is read through - [`HasField()`][google.protobuf.message.Message.HasField], so a token the - server actually sent is preserved even when it is empty; only an unset - token becomes `None`. + Unlike + [`pagination_info_from_proto`][frequenz.client.common.pagination.proto.v1alpha8.pagination_info_from_proto], + the token is read through [`HasField()`][google.protobuf.message.Message.HasField], + so a token the server actually sent is preserved even when it is empty; only an + unset token becomes `None`. Args: message: The protobuf message to convert. Returns: - A [`PaginationInfo`][....PaginationInfo] when the wire data is - well-formed, or an - [`InvalidPaginationInfo`][....InvalidPaginationInfo] preserving a - `total_items` count that violates `total_items >= 0`. + A [`PaginationInfo`][frequenz.client.common.pagination.PaginationInfo] when the + wire data is well-formed, or an + [`InvalidPaginationInfo`][frequenz.client.common.pagination.InvalidPaginationInfo] + preserving a `total_items` count that violates `total_items >= 0`. """ next_page_token = ( message.next_page_token if message.HasField("next_page_token") else None @@ -78,10 +80,11 @@ def pagination_info_from_proto2( def pagination_info_to_proto(info: PaginationInfo) -> PaginationInfoPb: - """Convert a [`PaginationInfo`][....PaginationInfo] object to a protobuf message. + """Convert a pagination info object to a protobuf message. Args: - info: The [`PaginationInfo`][....PaginationInfo] object to convert. + info: The [`PaginationInfo`][frequenz.client.common.pagination.PaginationInfo] + object to convert. Returns: The corresponding protobuf message. diff --git a/src/frequenz/client/common/proto/_datetime.py b/src/frequenz/client/common/proto/_datetime.py index 80bf1f0c..9361668b 100644 --- a/src/frequenz/client/common/proto/_datetime.py +++ b/src/frequenz/client/common/proto/_datetime.py @@ -69,13 +69,13 @@ def datetime_from_proto( # noqa: DOC502 """Convert a protobuf Timestamp to a datetime. Warning: Deprecated - Use [`datetime_from_proto2`][..datetime_from_proto2] instead. The new - conversion function keeps a malformed timestamp in its return type - (`datetime | InvalidDatetime`) rather than raising or silently - repairing it, and is exact across the whole protobuf range, where this - function loses sub-second precision far from the epoch. It always - returns UTC; call [`astimezone()`][datetime.datetime.astimezone] on the - result instead of passing `tz`. + Use [`datetime_from_proto2`][frequenz.client.common.proto.datetime_from_proto2] + instead. The new conversion function keeps a malformed timestamp in its return + type (`datetime | InvalidDatetime`) rather than raising or silently repairing + it, and is exact across the whole protobuf range, where this function loses + sub-second precision far from the epoch. It always returns UTC; call + [`astimezone()`][datetime.datetime.astimezone] on the result instead of passing + `tz`. Args: ts: The Timestamp object to convert. diff --git a/src/frequenz/client/common/streaming/proto/v1alpha8/_event.py b/src/frequenz/client/common/streaming/proto/v1alpha8/_event.py index 020a291d..4535efc8 100644 --- a/src/frequenz/client/common/streaming/proto/v1alpha8/_event.py +++ b/src/frequenz/client/common/streaming/proto/v1alpha8/_event.py @@ -10,23 +10,24 @@ def event_from_proto(message: event_pb2.Event.ValueType) -> Event | int: - """Convert a protobuf `Event` value to a [`Event`][....Event] enum member. + """Convert a protobuf `Event` value to an enum member. Args: message: The protobuf message to convert. Returns: - The corresponding [`Event`][....Event] enum member, or the raw [`int`][] - if the protobuf value is not recognized. + The corresponding [`Event`][frequenz.client.common.streaming.Event] enum member, + or the raw [`int`][] if the protobuf value is not recognized. """ return enum_from_proto(message, Event) def event_to_proto(event: Event) -> event_pb2.Event.ValueType: - """Convert a [`Event`][....Event] enum member to a protobuf value. + """Convert an enum member to a protobuf `Event` value. Args: - event: The enum member to convert. + event: The [`Event`][frequenz.client.common.streaming.Event] enum member to + convert. Returns: The corresponding protobuf `Event` value. diff --git a/src/frequenz/client/common/test/enum_parity.py b/src/frequenz/client/common/test/enum_parity.py index ec1fc369..e8a78b42 100644 --- a/src/frequenz/client/common/test/enum_parity.py +++ b/src/frequenz/client/common/test/enum_parity.py @@ -13,10 +13,10 @@ * There is a versioned `_to_proto` function returning the numeric protobuf value. -[`EnumParityTest`][.EnumParityTest] is a parametrized [`pytest`][pytest] -base class covering all those invariants. New enum wrappers add a one-line -subclass that pins the protobuf-specific attributes instead of copy-pasting -the same scaffold. +[`EnumParityTest`][frequenz.client.common.test.enum_parity.EnumParityTest] is a +parametrized [`pytest`][pytest] base class covering all those invariants. New enum +wrappers add a one-line subclass that pins the protobuf-specific attributes instead of +copy-pasting the same scaffold. """ from __future__ import annotations @@ -33,19 +33,24 @@ class EnumParityTest: """Base test class checking protobuf/Python enum parity. - Subclasses must set [`python_enum`][.python_enum], - [`proto_enum`][.proto_enum], [`name_prefix`][.name_prefix], - [`from_proto`][.from_proto] and [`to_proto`][.to_proto]. The subclass - name must start with `Test` so [`pytest`][pytest] picks it up. + Subclasses must set + [`python_enum`][frequenz.client.common.test.enum_parity.EnumParityTest.python_enum], + [`proto_enum`][frequenz.client.common.test.enum_parity.EnumParityTest.proto_enum], + [`name_prefix`][frequenz.client.common.test.enum_parity.EnumParityTest.name_prefix], + [`from_proto`][frequenz.client.common.test.enum_parity.EnumParityTest.from_proto] + and [`to_proto`][frequenz.client.common.test.enum_parity.EnumParityTest.to_proto]. + The subclass name must start with `Test` so [`pytest`][pytest] picks it up. For each subclass, the inherited tests verify that: * every protobuf enum name maps to a Python enum member with the same value (tolerating new protobuf values not yet mirrored in Python); * every Python enum member maps to a protobuf enum name and value; - * [`from_proto`][.from_proto] returns the matching member for known values - and the raw [`int`][] for unknown values; - * [`to_proto`][.to_proto] returns the numeric protobuf value. + * [`from_proto`][frequenz.client.common.test.enum_parity.EnumParityTest.from_proto] + returns the matching member for known values and the raw [`int`][] for unknown + values; + * [`to_proto`][frequenz.client.common.test.enum_parity.EnumParityTest.to_proto] + returns the numeric protobuf value. Info: Deprecation-aware mode Subclasses may pin `deprecated_members` and/or `absent_members` to make @@ -115,21 +120,28 @@ class TestEventParity(EnumParityTest): """ deprecated_members: ClassVar[frozenset[str]] = frozenset() - """The names of members (without [`name_prefix`][..name_prefix]) expected to be deprecated. + """The names of members expected to be deprecated. + The names don't include the + [`name_prefix`][frequenz.client.common.test.enum_parity.EnumParityTest.name_prefix]. Accessing them must emit a [`DeprecationWarning`][]. """ absent_members: ClassVar[frozenset[str]] = frozenset() - """The names of members (without [`name_prefix`][..name_prefix]) expected to be absent. + """The names of members expected to be absent. + The names don't include the + [`name_prefix`][frequenz.client.common.test.enum_parity.EnumParityTest.name_prefix]. These members are expected to be absent from the Python enum while still defined in the protobuf enum. """ silence_deprecations: ClassVar[bool] = False - """Whether the [`from_proto`][..from_proto]/[`to_proto`][..to_proto] converters are deprecated. + """Whether the converters are deprecated. + The converters are + [`from_proto`][frequenz.client.common.test.enum_parity.EnumParityTest.from_proto] + and [`to_proto`][frequenz.client.common.test.enum_parity.EnumParityTest.to_proto]. When `True`, the parity checks suppress the `DeprecationWarning` emitted by calling them (member-level deprecation checks are unaffected). """ diff --git a/src/frequenz/client/common/types/_location.py b/src/frequenz/client/common/types/_location.py index 848f9a5b..d73caf1c 100644 --- a/src/frequenz/client/common/types/_location.py +++ b/src/frequenz/client/common/types/_location.py @@ -181,20 +181,22 @@ def __str__(self) -> str: class Location: """A location's information. - Instances carry the raw wire values of a protobuf `Location` message. - Invalid or absent field values are expressed in the type system: - [`latitude`][.latitude] and [`longitude`][.longitude] may be - [`InvalidLatitude`][..InvalidLatitude] or - [`InvalidLongitude`][..InvalidLongitude]; - [`country_code`][.country_code] may be - [`InvalidCountryCode`][..InvalidCountryCode] or `None` when the field - was unset on the wire. Users can pattern-match on the fields directly, - or call [`get_latitude()`][.get_latitude], - [`get_longitude()`][.get_longitude], - [`get_country_code()`][.get_country_code] and - [`get_country_code_or_none()`][.get_country_code_or_none] to obtain a - validated value or a clear - [`InvalidAttributeError`][...InvalidAttributeError] subclass. + Instances carry the raw wire values of a protobuf `Location` message. Invalid or + absent field values are expressed in the type system: + [`latitude`][frequenz.client.common.types.Location.latitude] and + [`longitude`][frequenz.client.common.types.Location.longitude] may be + [`InvalidLatitude`][frequenz.client.common.types.InvalidLatitude] or + [`InvalidLongitude`][frequenz.client.common.types.InvalidLongitude]; + [`country_code`][frequenz.client.common.types.Location.country_code] may be + [`InvalidCountryCode`][frequenz.client.common.types.InvalidCountryCode] or `None` + when the field was unset on the wire. Users can pattern-match on the fields + directly, or call + [`get_latitude()`][frequenz.client.common.types.Location.get_latitude], + [`get_longitude()`][frequenz.client.common.types.Location.get_longitude], + [`get_country_code()`][frequenz.client.common.types.Location.get_country_code] and + [`get_country_code_or_none()`][frequenz.client.common.types.Location.get_country_code_or_none] + to obtain a validated value or a clear + [`InvalidAttributeError`][frequenz.client.common.InvalidAttributeError] subclass. Constructing a `Location` with a plain number or `str` that violates its invariant raises `ValueError`; use the corresponding `Invalid*` @@ -205,38 +207,41 @@ class Location: """The latitude. A plain number when well-formed (in `[-90, 90]`); an - [`InvalidLatitude`][...InvalidLatitude] wrapper when the wire delivered - an out-of-range value. + [`InvalidLatitude`][frequenz.client.common.types.InvalidLatitude] wrapper when the + wire delivered an out-of-range value. Tip: - Use [`Location.get_latitude()`][...Location.get_latitude] to obtain - a validated number or a clear error. + Use + [`Location.get_latitude()`][frequenz.client.common.types.Location.get_latitude] + to obtain a validated number or a clear error. """ longitude: FloatInt | InvalidLongitude """The longitude. A plain number when well-formed (in `[-180, 180]`); an - [`InvalidLongitude`][...InvalidLongitude] wrapper when the wire - delivered an out-of-range value. + [`InvalidLongitude`][frequenz.client.common.types.InvalidLongitude] wrapper when the + wire delivered an out-of-range value. Tip: - Use [`Location.get_longitude()`][...Location.get_longitude] to obtain a - validated number or a clear error. + Use + [`Location.get_longitude()`][frequenz.client.common.types.Location.get_longitude] + to obtain a validated number or a clear error. """ country_code: str | InvalidCountryCode | None """The country code. - A plain `str` (exactly 2 characters, ISO 3166-1 Alpha-2) when - well-formed; an [`InvalidCountryCode`][...InvalidCountryCode] wrapper - when the wire delivered a non-empty string of a different length; - `None` when the field was unset on the wire (an empty string on the - wire is normalized to `None` by the converter). + A plain `str` (exactly 2 characters, ISO 3166-1 Alpha-2) when well-formed; an + [`InvalidCountryCode`][frequenz.client.common.types.InvalidCountryCode] wrapper when + the wire delivered a non-empty string of a different length; `None` when the field + was unset on the wire (an empty string on the wire is normalized to `None` by the + converter). Tip: - Use [`Location.get_country_code()`][...Location.get_country_code] to - obtain a validated `str` or a clear error. + Use + [`Location.get_country_code()`][frequenz.client.common.types.Location.get_country_code] + to obtain a validated `str` or a clear error. """ def __post_init__(self) -> None: @@ -281,9 +286,10 @@ def get_latitude(self) -> FloatInt: The latitude, when it is a well-formed number. Raises: - InvalidLatitudeError: If [`latitude`][..latitude] is an - [`InvalidLatitude`][...InvalidLatitude]. The raw value is - available on the exception's `value` attribute. + InvalidLatitudeError: If + [`latitude`][frequenz.client.common.types.Location.latitude] is an + [`InvalidLatitude`][frequenz.client.common.types.InvalidLatitude]. The + raw value is available on the exception's `value` attribute. """ match self.latitude: case InvalidLatitude(value=raw): @@ -300,9 +306,10 @@ def get_longitude(self) -> FloatInt: The longitude, when it is a well-formed number. Raises: - InvalidLongitudeError: If [`longitude`][..longitude] is an - [`InvalidLongitude`][...InvalidLongitude]. The raw value is - available on the exception's `value` attribute. + InvalidLongitudeError: If + [`longitude`][frequenz.client.common.types.Location.longitude] is an + [`InvalidLongitude`][frequenz.client.common.types.InvalidLongitude]. The + raw value is available on the exception's `value` attribute. """ match self.longitude: case InvalidLongitude(value=raw): @@ -319,11 +326,14 @@ def get_country_code(self) -> str: The country code, when it is a well-formed `str`. Raises: - MissingFieldError: If [`country_code`][..country_code] is + MissingFieldError: If + [`country_code`][frequenz.client.common.types.Location.country_code] is `None` (the field was not set on the wire). - InvalidCountryCodeError: If [`country_code`][..country_code] is - an [`InvalidCountryCode`][...InvalidCountryCode]. The raw - value is available on the exception's `value` attribute. + InvalidCountryCodeError: If + [`country_code`][frequenz.client.common.types.Location.country_code] is + an + [`InvalidCountryCode`][frequenz.client.common.types.InvalidCountryCode]. + The raw value is available on the exception's `value` attribute. """ match self.country_code: case None: @@ -340,10 +350,11 @@ def get_country_code_or_none( ) -> str | None: """Return the country code as a well-formed `str`, or `None` if unset. - Same as [`get_country_code()`][..get_country_code] but returns - `None` instead of raising `MissingFieldError` when - [`country_code`][..country_code] is `None` (the field was not set - on the wire). Invalid country codes still raise + Same as + [`get_country_code()`][frequenz.client.common.types.Location.get_country_code] + but returns `None` instead of raising `MissingFieldError` when + [`country_code`][frequenz.client.common.types.Location.country_code] is `None` + (the field was not set on the wire). Invalid country codes still raise `InvalidCountryCodeError`. Returns: @@ -351,9 +362,11 @@ def get_country_code_or_none( was not set on the wire). Raises: - InvalidCountryCodeError: If [`country_code`][..country_code] is - an [`InvalidCountryCode`][...InvalidCountryCode]. The raw - value is available on the exception's `value` attribute. + InvalidCountryCodeError: If + [`country_code`][frequenz.client.common.types.Location.country_code] is + an + [`InvalidCountryCode`][frequenz.client.common.types.InvalidCountryCode]. + The raw value is available on the exception's `value` attribute. """ match self.country_code: case None: diff --git a/src/frequenz/client/common/types/proto/v1alpha8/_location.py b/src/frequenz/client/common/types/proto/v1alpha8/_location.py index 9c6c3bcc..f4ad2e74 100644 --- a/src/frequenz/client/common/types/proto/v1alpha8/_location.py +++ b/src/frequenz/client/common/types/proto/v1alpha8/_location.py @@ -14,18 +14,18 @@ def location_from_proto(message: location_pb2.Location) -> Location: - """Convert a protobuf message to a [`Location`][....Location] object. + """Convert a protobuf message to a location object. The returned instance carries the raw wire values with the following normalization applied: * Latitude and longitude are wrapped in - [`InvalidLatitude`][....InvalidLatitude] and - [`InvalidLongitude`][....InvalidLongitude] respectively when they - fall outside their well-formed ranges. - * An empty `country_code` on the wire is normalized to `None`; a - non-empty `country_code` that is not exactly 2 characters long is - wrapped in [`InvalidCountryCode`][....InvalidCountryCode]. + [`InvalidLatitude`][frequenz.client.common.types.InvalidLatitude] and + [`InvalidLongitude`][frequenz.client.common.types.InvalidLongitude] respectively + when they fall outside their well-formed ranges. + * An empty `country_code` on the wire is normalized to `None`; a non-empty + `country_code` that is not exactly 2 characters long is wrapped in + [`InvalidCountryCode`][frequenz.client.common.types.InvalidCountryCode]. Use the `get_*()` accessors on the returned instance to obtain validated values or a clear `InvalidAttributeError` subclass. @@ -34,7 +34,7 @@ def location_from_proto(message: location_pb2.Location) -> Location: message: The protobuf message to convert. Returns: - The resulting [`Location`][....Location] object. + The resulting [`Location`][frequenz.client.common.types.Location] object. """ latitude: float | InvalidLatitude = ( message.latitude diff --git a/tests/grid/_delivery_area/test_delivery_area.py b/tests/grid/_delivery_area/test_delivery_area.py index eb9b5c1b..79afd057 100644 --- a/tests/grid/_delivery_area/test_delivery_area.py +++ b/tests/grid/_delivery_area/test_delivery_area.py @@ -122,12 +122,13 @@ def test_creation_with_int_zero_code_type_emits_deprecation_warning() -> None: def test_creation_with_unspecified_code_type_member_emits_deprecation_warning() -> None: """`__post_init__` warns when `code_type` is the UNSPECIFIED member. - Accessing [`EnergyMarketCodeType.UNSPECIFIED`][...EnergyMarketCodeType] itself - emits its own `DeprecationWarning`; this test confirms that constructing a - `DeliveryArea` with a valid `code` and that pre-accessed member also triggers - the `__post_init__` invariant warning. Consistent with the `int(0)` case - above, `DeliveryArea` renders the enum name bare — the invalidity marker - only appears on `InvalidDeliveryArea`. + Accessing + [`EnergyMarketCodeType.UNSPECIFIED`][frequenz.client.common.grid.EnergyMarketCodeType.UNSPECIFIED] + itself emits its own `DeprecationWarning`; this test confirms that constructing a + `DeliveryArea` with a valid `code` and that pre-accessed member also triggers the + `__post_init__` invariant warning. Consistent with the `int(0)` case above, + `DeliveryArea` renders the enum name bare — the invalidity marker only appears on + `InvalidDeliveryArea`. """ with pytest.deprecated_call(): unspecified = EnergyMarketCodeType.UNSPECIFIED From 025e2134db4a795f44d500dae8daf3df63cd7a68 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 23 Oct 2026 12:28:40 +0000 Subject: [PATCH 2/4] Disable mkdocstrings relative cross-references No docstring uses relative cross-references anymore, so the option is removed to stop new ones from being added. Absolute references to public paths are the convention from now on. See frequenz-floss/frequenz-repo-config-python#655 for details. Signed-off-by: Leandro Lucarella --- mkdocs.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/mkdocs.yml b/mkdocs.yml index 73a4c8d5..e36cd40c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -108,7 +108,6 @@ plugins: docstring_section_style: spacy inherited_members: true merge_init_into_class: false - relative_crossrefs: true separate_signature: true show_category_heading: true show_root_heading: true From e26112e9575034f4e6b03469166524943fd3fb2a Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 23 Oct 2026 12:28:40 +0000 Subject: [PATCH 3/4] Update release notes Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 35ea0f5e..3d36bb76 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -248,3 +248,4 @@ There are a few intentional hard breaks too, all listed in the Upgrading section * Fixed `EnumParityTest` so protobuf values whose Python member name exists with a different number fail parity checks instead of being treated as unmirrored protobuf values. * Fixed potential unexpected exceptions due to type-checking accepting `int` for code annotated to only accept `float`. Fixes #250. * Exception messages reporting an invalid value now use its `str()` instead of its `repr()`, so they show the compact `` rendering instead of a verbose dataclass dump. +* Docstrings now use absolute cross-references to public paths instead of relative ones. Relative cross-references are expanded from the module where an object is defined since mkdocstrings-python 2.0.9, which broke many links, and projects rendering docstrings inherited from this library needed `relative_crossrefs: true` for them to work at all. See [frequenz-repo-config-python#655](https://github.com/frequenz-floss/frequenz-repo-config-python/issues/655) for details. From 4449b950c43e93cd5998bb84bb67c9c88ab14c24 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 23 Oct 2026 12:28:40 +0000 Subject: [PATCH 4/4] Bump mkdocstrings to 1.0.7 pymdown-extensions 12.2 added a required `md` argument to `pymdownx.highlight.Highlight.__init__()`, which mkdocstrings 1.0.6 subclasses without passing it. pymdown-extensions is only a transitive dependency, so it floated to the new version and every docs build now fails with: TypeError: Highlight.__init__() missing 1 required positional argument: 'md' mkdocstrings 1.0.7 passes `md` when the parent accepts it (mkdocstrings/mkdocstrings#829). 1.0.8 is out too, but it changes the code anchor IDs, so it is left for its own bump. Signed-off-by: Leandro Lucarella --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 6d94ac2b..293be201 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,7 +55,7 @@ dev-mkdocs = [ "mkdocs-literate-nav == 0.6.3", "mkdocs-macros-plugin == 1.5.0", "mkdocs-material == 9.7.7", - "mkdocstrings[python] == 1.0.6", + "mkdocstrings[python] == 1.0.7", "mkdocstrings-python == 2.0.7", "frequenz-repo-config[lib] == 0.19.0", ]