Skip to content

Decorators

Common assertions for convenience

Classes:

ROS()Decorators to get boilerplate code out of the Nodes to make it easier to see what comes in, what goes out, and what gets transformed.
TOriginal return type of the wrapped method

Functions:

cache_if(predicate)A decorator to cache the return value of a property, storing the result with the same name as the decorated member but with a leading underscore.
narrow_types([arg, return_value])Function decorator to narrow provided argument types to match the decorated method's type hints in a ``mypy`` compatible way.

class gisnav._decorators.ROS

Bases: object

Decorators to get boilerplate code out of the Nodes to make it easier to see what comes in, what goes out, and what gets transformed.

Attributes:

SUPPORTED_ROS_TYPES

Methods:

max_delay_ms(max_time_diff_ms)A decorator that checks the property's ROS header timestamp and compares it to the current clock.
parameter(default_value[, descriptor])Decorator for declaring a property as a ROS parameter in a ROS node.
publish(topic_name, qos)A decorator to create a managed attribute (property) that publishes its value over a ROS topic whenever it's called.
subscribe(topic_name, qos[, callback])A decorator to create a managed attribute (property) that subscribes to a ROS topic with the same type as the property.
transform([child_frame_id, invert])A decorator to wrap a method that returns a PoseStamped or a TransformStamped message, converts it to a TransformStamped if needed, and then publishes it on the tf topic.

SUPPORTED_ROS_TYPES = (<class 'str'>, <class 'int'>, <class 'float'>, <class 'bool'>, typing.List[str], typing.List[int], typing.List[float], typing.List[bool])

static max_delay_ms(max_time_diff_ms: int)

A decorator that checks the property’s ROS header timestamp and compares it to the current clock. If the time difference is larger than what is provided to the decorator (in milliseconds), the decorated function logs a warning and returns None instead.

  • Parameters:max_time_diff_ms – Maximum allowed time difference in milliseconds.
  • Returns: The wrapped function or method with added timestamp checking. The decorated function returns None if the timestamp is too old.

static parameter(default_value: str | int | float | bool | List[str] | List[int] | List[float] | List[bool], descriptor: ParameterDescriptor | None = None)

Decorator for declaring a property as a ROS parameter in a ROS node. It uses the name of the property for the parameter name and the return type hint for the parameter type.

  • Parameters:
    • default_value – Default value for parameter
    • descriptor – Optional parameter descriptor
  • Returns: Decorator function
  • Raises:ValueError – If the decorator is not used in a ROS node

static publish(topic_name: str, qos)

A decorator to create a managed attribute (property) that publishes its value over a ROS topic whenever it’s called.

  • Parameters:
    • topic_name – The name of the ROS topic to publish to.
    • qos – The Quality of Service settings for the topic publishing.
  • Returns: A property that publishes its value to the specified ROS topic whenever the property is called

static subscribe(topic_name: str, qos, callback=None)

A decorator to create a managed attribute (property) that subscribes to a ROS topic with the same type as the property. The property should be an optional type, e.g. Optional[Altitude], where a None value indicates the message has not been received yet. The decorator also supports defining an optional callback method.

TODO: enforce or check optional type

Example usage:

python
from mavros_msgs.msg import Altitude
from typing import Optional

from . import messaging

class AutopilotNode:
    ...

    @property
    @ROS.subscribe(messaging.ROS_TOPIC_TERRAIN_ALTITUDE, 10)
    def terrain_altitude(self) -> Optional[Altitude]:
        pass

    def on_message(self, msg: Altitude):
        pass

In this example, the terrain_altitude property subscribes to the messaging.ROS_TOPIC_TERRAIN_ALTITUDE ROS topic. The on_message callback will be executed every time a new Altitude message is received.

  • Parameters:
    • topic_name – The name of the ROS topic to subscribe to.
    • qos – The Quality of Service settings for the topic subscription.
    • callback – An optional callback method to be executed when a new message is received.
  • Returns: A property that holds the latest message from the specified ROS topic, or None if no messages have been received yet.

static transform(child_frame_id: str | None = None, invert: bool = True)

A decorator to wrap a method that returns a PoseStamped or a TransformStamped message, converts it to a TransformStamped if needed, and then publishes it on the tf topic.

  • Parameters:
    • child_frame_id – Name of child frame
    • invert – Set to False to not invert the transform relative to the pose. Inverting the pose is useful if the frame_id of the pose needs to be the child_frame_id in the tf transformation tree (e.g. in a situation where the input child_frame_id already has a parent in the tf tree).
  • Returns: A method that publishes its return value to the tf topic whenever called. The return value must be TransformStamped, PoseStamped, or None

class gisnav._decorators.T

Original return type of the wrapped method

alias of TypeVar(‘T’)

gisnav._decorators.cache_if(predicate)

A decorator to cache the return value of a property, storing the result with the same name as the decorated member but with a leading underscore. The decorator takes a callable (predicate function) as input that determines whether the property method will be executed or if the cached value will be returned instead.

WARNING

You cannot use the property or method you are wrapping inside the predicate directly. If you need to use the cached value of the property you are wrapping inside the predicate, access the cached private attribute directly to prevent infinite recursion (e.g. self._my_property instead of self.my_property).

Example usage:

python
class MyClass:
    @property
    @cache_if(some_predicate_function)
    def my_property(self):
        # Your implementation
  • Parameters:predicate (callable) – A callable that takes the instance as its only argument and returns a boolean, indicating whether the property should be evaluated (True) or if the cached value should be returned (False)

gisnav._decorators.narrow_types(arg: Callable[[...], T] | Node | None = None, return_value: Any | None = None)

Function decorator to narrow provided argument types to match the decorated method’s type hints in a ``mypy`` compatible way. Can also be used to enforce types at runtime (which is a more exotic use case). Can be used on an instance method, or a static method if the node_instance argument is provided (None by default).

If any of the arguments do not match their corresponding type hints, this decorator logs the mismatches and then returns None without executing the original method. Otherwise, it proceeds to call the original method with the given arguments and keyword arguments.

WARNING

  • If the decorated method can also return None after execution you will not be able to tell from the return value whether the method executed or the type narrowing failed. In this case, you specify a different return value using the optional input argument.

NOTE

This decorator is mainly used to streamline computed properties by automating the check for required instance properties with e.g. None values. It eliminates repetitive code and logs warning messages when a property cannot be computed, resulting in cleaner property implementations with less boilerplate code.

  • Parameters:
    • arg – Node instance that provides the logger if this decorator is used to wrap e.g. a static or class method, of the wrapped method if this wraps an instance method
    • return_value – Optional custom return value to replace default None if the types narrowing fails
  • Returns: The return value of the original method or parameter return_value if any argument does not match the type hints.

GISNav v0.68.1-2-gf2c72641

Released under the MIT License.