fedbiomed.common.message

Module: fedbiomed.common.message

Definition of messages exchanged by the researcher and the nodes

Classes

AddScalarReply dataclass

Bases: Message

Describes a add_scalar message sent by the node.

Attributes:

Name Type Description
researcher_id str

ID of the researcher that receives the reply

job_id str

ID of the Job that is sent by researcher

train bool

Declares whether scalar value is for training

test bool

Declares whether scalar value is for validation

test_on_local_updates bool

Declares whether validation is performed over locally updated parameters

test_on_global_updates bool

Declares whether validation is performed over aggregated parameters

metric dict

Evaluation metroc

epoch int, type(None)

Scalar is received at

total_samples int

Number of all samples in dataset

batch_samples int

Number of samples in batch

num_batches int

Number of batches in single epoch

iteration int

Scalar is received at

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

batch_samples class-attribute
batch_samples: int
command class-attribute
command: str
epoch class-attribute
epoch: int, type(None)
iteration class-attribute
iteration: int
job_id class-attribute
job_id: str
metric class-attribute
metric: dict
node_id class-attribute
node_id: str
num_batches class-attribute
num_batches: int
num_samples_trained class-attribute
num_samples_trained: int, type(None)
researcher_id class-attribute
researcher_id: str
test class-attribute
test: bool
test_on_global_updates class-attribute
test_on_global_updates: bool
test_on_local_updates class-attribute
test_on_local_updates: bool
total_samples class-attribute
total_samples: int
train class-attribute
train: bool

ApprovalReply dataclass

Bases: Message

Describes the TrainingPlan approval reply (acknoledge) from node to researcher.

Attributes:

Name Type Description
researcher_id str

Id of the researcher that will receive the reply

node_id str

Node id that replys the request

sequence int

sequence number of the corresponding request

status int

status code received after uploading the training plan (usually HTTP status)

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str
sequence class-attribute
sequence: int
status class-attribute
status: int
success class-attribute
success: bool

ApprovalRequest dataclass

Bases: Message

Describes the TrainingPlan approval request from researcher to node.

Attributes:

Name Type Description
researcher_id str

id of the researcher that sends the request

description str

description of the training plan

sequence int

(unique) sequence number which identifies the message

training_plan_url str

URL where TrainingPlan is available

command str

request command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
description class-attribute
description: str
researcher_id class-attribute
researcher_id: str
sequence class-attribute
sequence: int
training_plan_url class-attribute
training_plan_url: str

ErrorMessage dataclass

Bases: Message

Describes an error message sent by the node.

Attributes:

Name Type Description
researcher_id str

ID of the researcher that receives the error message

node_id str

ID of the node that sends error message

errnum ErrorNumbers

Error ID/Number

extra_msg str

Additional message regarding the error

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
errnum class-attribute
errnum: ErrorNumbers
extra_msg class-attribute
extra_msg: str
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str

ListReply dataclass

Bases: Message

This class describes a list reply message sent by the node that includes list of datasets. It is a reply for ListRequest message from the researcher.

Attributes:

Name Type Description
researcher_id str

Id of the researcher that sends the request

succes str

True if the node process the request as expected, false if any exception occurs

databases list

List of datasets

node_id str

Node id that replys the request

count int

Number of datasets

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
count class-attribute
count: int
databases class-attribute
databases: list
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str
success class-attribute
success: bool

ListRequest dataclass

Bases: Message

Describes a list request message sent by the researcher to nodes in order to list datasets belonging to each node.

Attributes:

Name Type Description
researcher_id str

Id of the researcher that sends the request

command str

Request command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
researcher_id class-attribute
researcher_id: str

LogMessage dataclass

Bases: Message

Describes a log message sent by the node.

Attributes:

Name Type Description
researcher_id str

ID of the researcher that will receive the log message

node_id str

ID of the node that sends log message

level str

Log level

msg str

Log message

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
level class-attribute
level: str
msg class-attribute
msg: str
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str

Message

Bases: object

Base class for all fedbiomed messages providing all methods to access the messages

The subclasses of this class will be pure data containers (no provided functions)

Functions

get_dict()

Returns pairs (Message class attributes name, attributes values) into a dictionary

Returns:

Type Description
Dict[str, Any]

Message as dictionary

Source code in fedbiomed/common/message.py
def get_dict(self) -> Dict[str, Any]:
    """Returns pairs (Message class attributes name, attributes values) into a dictionary

    Returns:
        Message as dictionary
    """
    return self.__dict__
get_param(param)

Get the value of a given param

Parameters:

Name Type Description Default
param str

name of the param

required
Source code in fedbiomed/common/message.py
def get_param(self, param: str):
    """Get the value of a given param

    Args:
        param: name of the param
    """
    return getattr(self, param)

NodeMessages

Allows to create the corresponding class instance from a received/sent message by the Node

Functions

reply_create(params)
classmethod

Message reception.

It creates the adequate message reply to send to the researcher, it maps an instruction (given the key "command" in the input dictionary params) to a Message object

It validates: - the legacy of the message - the structure of the received message

Raises:

Type Description
FedbiomedMessageError

if the message is not allowed te be received by the node (ie if message command field is not either a train request, search request, a ping request, add scalar request, or error message)

Returns:

Type Description
Union[TrainReply, SearchReply, PingReply, LogMessage, ErrorMessage, AddScalarReply, ListReply, TrainingPlanStatusReply, ApprovalReply, SecaggReply, SecaggDeleteReply]

An instance of the corresponding class

Source code in fedbiomed/common/message.py
@classmethod
def reply_create(cls, params: dict) -> Union[TrainReply,
                                             SearchReply,
                                             PingReply,
                                             LogMessage,
                                             ErrorMessage,
                                             AddScalarReply,
                                             ListReply,
                                             TrainingPlanStatusReply,
                                             ApprovalReply,
                                             SecaggReply,
                                             SecaggDeleteReply]:
    """Message reception.

    It creates the adequate message reply to send to the researcher, it maps an instruction (given the key
    "command" in the input dictionary `params`) to a Message object

    It validates:
    - the legacy of the message
    - the structure of the received message

    Raises:
        FedbiomedMessageError: if the message is not allowed te be received by the node (ie if message `command`
            field is not either a train request, search request, a ping request, add scalar request, or
            error message)

    Returns:
        An instance of the corresponding class
    """
    try:
        message_type = params['command']
    except KeyError:
        _msg = ErrorNumbers.FB601.value + ": message type not specified"
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)

    MESSAGE_TYPE_TO_CLASS_MAP = {'train': TrainReply,
                                 'search': SearchReply,
                                 'pong': PingReply,
                                 'log': LogMessage,
                                 'error': ErrorMessage,
                                 'add_scalar': AddScalarReply,
                                 'list': ListReply,
                                 'training-plan-status': TrainingPlanStatusReply,
                                 'approval': ApprovalReply,
                                 'secagg': SecaggReply,
                                 'secagg-delete': SecaggDeleteReply
                                 }

    if message_type not in MESSAGE_TYPE_TO_CLASS_MAP:
        _msg = ErrorNumbers.FB601.value + ": bad message type for request_create: {}".format(message_type)
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)
    return MESSAGE_TYPE_TO_CLASS_MAP[message_type](**params)
request_create(params)
classmethod

Creates the adequate message/ request to send to researcher, it maps an instruction (given the key "command" in the input dictionary params) to a Message object

It validates: - the legacy of the message - the structure of the created message

Raises:

Type Description
FedbiomedMessageError

triggered if the message is not allowed te be sent by the node (ie if message command field is not either a train request, search request or a ping request)

Returns:

Type Description
Union[TrainRequest, SearchRequest, PingRequest, ListRequest, TrainingPlanStatusRequest, ApprovalRequest, SecaggRequest, SecaggDeleteRequest]

An instance of the corresponding class (TrainRequest,SearchRequest, PingRequest)

Source code in fedbiomed/common/message.py
@classmethod
def request_create(cls, params: dict) -> Union[TrainRequest,
                                               SearchRequest,
                                               PingRequest,
                                               ListRequest,
                                               TrainingPlanStatusRequest,
                                               ApprovalRequest,
                                               SecaggRequest,
                                               SecaggDeleteRequest]:
    """Creates the adequate message/ request to send to researcher, it maps an instruction (given the key
    "command" in the input dictionary `params`) to a Message object

    It validates:
    - the legacy of the message
    - the structure of the created message

    Raises:
        FedbiomedMessageError: triggered if the message is not allowed te be sent by the node (ie if message
            `command` field is not either a train request, search request or a ping request)

    Returns:
        An instance of the corresponding class (TrainRequest,SearchRequest, PingRequest)
    """
    try:
        message_type = params['command']
    except KeyError:
        _msg = ErrorNumbers.FB601.value + ": message type not specified"
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)

    # mapping message type to an object
    MESSAGE_TYPE_TO_CLASS_MAP = {'train': TrainRequest,
                                 'search': SearchRequest,
                                 'ping': PingRequest,
                                 'list': ListRequest,
                                 'training-plan-status': TrainingPlanStatusRequest,
                                 'approval': ApprovalRequest,
                                 'secagg': SecaggRequest,
                                 'secagg-delete': SecaggDeleteRequest
                                 }

    if message_type not in MESSAGE_TYPE_TO_CLASS_MAP:
        _msg = ErrorNumbers.FB601.value + ": bad message type for reply_create: {}".format(message_type)
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)
    return MESSAGE_TYPE_TO_CLASS_MAP[message_type](**params)

PingReply dataclass

Bases: Message

This class describes a ping message sent by the node.

Attributes:

Name Type Description
researcher_id str

Id of the researcher that will receive the reply

node_id str

Node id that replys the request

succes str

True if the node process the request as expected, false if any exception occurs

sequence int

Ping sequence

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str
sequence class-attribute
sequence: int
success class-attribute
success: bool

PingRequest dataclass

Bases: Message

Describes a ping message sent by the researcher

Attributes:

Name Type Description
researcher_id str

Id of the researcher that send ping reqeust

sequence int

Ping sequence

command str

Request command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
researcher_id class-attribute
researcher_id: str
sequence class-attribute
sequence: int

ResearcherMessages

Allows to create the corresponding class instance from a received/sent message by the researcher.

Functions

reply_create(params)
classmethod

Message reception (as a mean to reply to node requests, such as a Ping request).

It creates the adequate message, it maps an instruction (given the key "command" in the input dictionary params) to a Message object

It validates: - the legacy of the message - the structure of the received message

Raises:

Type Description
FedbiomedMessageError

triggered if the message is not allowed to be received by the researcher

KeyError

triggered if 'command' field is not present in params

Returns:

Type Description
Union[TrainReply, SearchReply, PingReply, LogMessage, ErrorMessage, ListReply, AddScalarReply, TrainingPlanStatusReply, ApprovalReply, SecaggReply, SecaggDeleteReply]

An instance of the corresponding Message class

Source code in fedbiomed/common/message.py
@classmethod
def reply_create(cls, params: Dict[str, Any]) -> Union[TrainReply,
                                                       SearchReply,
                                                       PingReply,
                                                       LogMessage,
                                                       ErrorMessage,
                                                       ListReply,
                                                       AddScalarReply,
                                                       TrainingPlanStatusReply,
                                                       ApprovalReply,
                                                       SecaggReply,
                                                       SecaggDeleteReply]:
    """Message reception (as a mean to reply to node requests, such as a Ping request).

    It creates the adequate message, it maps an instruction (given the key "command" in the input dictionary
    `params`) to a Message object

    It validates:
    - the legacy of the message
    - the structure of the received message

    Raises:
        FedbiomedMessageError: triggered if the message is not allowed to be received by the researcher
        KeyError: triggered if 'command' field is not present in `params`

    Returns:
        An instance of the corresponding Message class
    """
    try:
        message_type = params['command']
    except KeyError:
        _msg = ErrorNumbers.FB601.value + ": message type not specified"
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)

    MESSAGE_TYPE_TO_CLASS_MAP = {'train': TrainReply,
                                 'search': SearchReply,
                                 'pong': PingReply,
                                 'log': LogMessage,
                                 'error': ErrorMessage,
                                 'list': ListReply,
                                 'add_scalar': AddScalarReply,
                                 'training-plan-status': TrainingPlanStatusReply,
                                 'approval': ApprovalReply,
                                 'secagg': SecaggReply,
                                 'secagg-delete': SecaggDeleteReply
                                 }

    if message_type not in MESSAGE_TYPE_TO_CLASS_MAP:
        _msg = ErrorNumbers.FB601.value + ": bad message type for reply_create: {}".format(message_type)
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)
    return MESSAGE_TYPE_TO_CLASS_MAP[message_type](**params)
request_create(params)
classmethod

Creates the adequate message/request,

It maps an instruction (given the key "command" in the input dictionary params) to a Message object

It validates: - the legacy of the message - the structure of the created message

Parameters:

Name Type Description Default
params Dict[str, Any]

dictionary containing the message.

required

Raises:

Type Description
FedbiomedMessageError

if the message is not allowed to be sent by the researcher

KeyError

Missing key ub the reqeust

Returns:

Type Description
Union[TrainRequest, SearchRequest, PingRequest, ListRequest, TrainingPlanStatusRequest, ApprovalRequest, SecaggRequest, SecaggDeleteRequest]

An instance of the corresponding Message class

Source code in fedbiomed/common/message.py
@classmethod
def request_create(cls, params: Dict[str, Any]) -> Union[TrainRequest,
                                                         SearchRequest,
                                                         PingRequest,
                                                         ListRequest,
                                                         TrainingPlanStatusRequest,
                                                         ApprovalRequest,
                                                         SecaggRequest,
                                                         SecaggDeleteRequest]:

    """Creates the adequate message/request,

    It maps an instruction (given the key "command" in the input dictionary `params`) to a Message object

    It validates:
    - the legacy of the message
    - the structure of the created message

    Args:
        params: dictionary containing the message.

    Raises:
        FedbiomedMessageError: if the message is not allowed to be sent by the researcher
        KeyError: Missing key ub the reqeust

    Returns:
        An instance of the corresponding Message class
    """

    try:
        message_type = params['command']
    except KeyError:
        _msg = ErrorNumbers.FB601.value + ": message type not specified"
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)

    MESSAGE_TYPE_TO_CLASS_MAP = {'train': TrainRequest,
                                 'search': SearchRequest,
                                 'ping': PingRequest,
                                 'list': ListRequest,
                                 'training-plan-status': TrainingPlanStatusRequest,
                                 'approval': ApprovalRequest,
                                 'secagg': SecaggRequest,
                                 'secagg-delete': SecaggDeleteRequest
                                 }

    if message_type not in MESSAGE_TYPE_TO_CLASS_MAP:
        _msg = ErrorNumbers.FB601.value + ": bad message type for request_create: {}".format(message_type)
        logger.error(_msg)
        raise FedbiomedMessageError(_msg)
    return MESSAGE_TYPE_TO_CLASS_MAP[message_type](**params)

SearchReply dataclass

Bases: Message

Describes a search message sent by the node

Attributes:

Name Type Description
researcher_id str

Id of the researcher that sends the request

succes str

True if the node process the request as expected, false if any exception occurs

databases list

List of datasets

node_id str

Node id that replys the request

count int

Number of datasets

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
count class-attribute
count: int
databases class-attribute
databases: list
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str
success class-attribute
success: bool

SearchRequest dataclass

Bases: Message

Describes a search message sent by the researcher.

Attributes:

Name Type Description
researcher_id str

ID of the researcher that sends the request

tags list

Tags for search request

command str

Request command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
researcher_id class-attribute
researcher_id: str
tags class-attribute
tags: list

SecaggDeleteReply dataclass

Bases: Message

Describes a secagg context element delete reply message sent by the node

Attributes:

Name Type Description
researcher_id str

ID of the researcher that requests deletion

secagg_id str

ID of secagg context element that is sent by researcher

sequence int

(unique) sequence number which identifies the message

success bool

True if the node process the request as expected, false if any exception occurs

node_id str

Node id that replies to the request

msg str

Custom message

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
msg class-attribute
msg: str
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str
secagg_id class-attribute
secagg_id: str
sequence class-attribute
sequence: int
success class-attribute
success: bool

SecaggDeleteRequest dataclass

Bases: Message

Describes a secagg context element delete request message sent by the researcher

Attributes:

Name Type Description
researcher_id str

ID of the researcher that requests deletion

secagg_id str

ID of secagg context element that is sent by researcher

sequence int

(unique) sequence number which identifies the message

element int

Type of secagg context element

job_id str, type(None)

Id of the Job to which this secagg context element is attached

command str

Request command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
element class-attribute
element: int
job_id class-attribute
job_id: str, type(None)
researcher_id class-attribute
researcher_id: str
secagg_id class-attribute
secagg_id: str
sequence class-attribute
sequence: int

SecaggReply dataclass

Bases: Message

Describes a secagg context element setup reply message sent by the node

Attributes:

Name Type Description
researcher_id str

ID of the researcher that requests setup

secagg_id str

ID of secagg context element that is sent by researcher

sequence int

(unique) sequence number which identifies the message

success bool

True if the node process the request as expected, false if any exception occurs

node_id str

Node id that replies to the request

msg str

Custom message

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
msg class-attribute
msg: str
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str
secagg_id class-attribute
secagg_id: str
sequence class-attribute
sequence: int
success class-attribute
success: bool

SecaggRequest dataclass

Bases: Message

Describes a secagg context element setup request message sent by the researcher

Attributes:

Name Type Description
researcher_id str

ID of the researcher that requests setup

secagg_id str

ID of secagg context element that is sent by researcher

sequence int

(unique) sequence number which identifies the message

element int

Type of secagg context element

job_id str, type(None)

Id of the Job to which this secagg context element is attached

parties list

List of parties participating to the secagg context element setup

command str

Request command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
element class-attribute
element: int
job_id class-attribute
job_id: str, type(None)
parties class-attribute
parties: list
researcher_id class-attribute
researcher_id: str
secagg_id class-attribute
secagg_id: str
sequence class-attribute
sequence: int

TrainReply dataclass

Bases: Message

Describes a train message sent by the node.

Attributes:

Name Type Description
researcher_id str

Id of the researcher that receives the reply

job_id str

Id of the Job that is sent by researcher

success bool

True if the node process the request as expected, false if any exception occurs

node_id str

Node id that replys the request

dataset_id str

id of the dataset that is used for training

params_url str

URL of parameters uploaded by node

timing dict

Timing statistics

msg str

Custom message

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
dataset_id class-attribute
dataset_id: str
job_id class-attribute
job_id: str
msg class-attribute
msg: str
node_id class-attribute
node_id: str
params_url class-attribute
params_url: str
researcher_id class-attribute
researcher_id: str
sample_size class-attribute
sample_size: int, type(None)
success class-attribute
success: bool
timing class-attribute
timing: dict

TrainRequest dataclass

Bases: Message

Describes a train message sent by the researcher

Attributes:

Name Type Description
researcher_id str

ID of the researcher that requests training

job_id str

Id of the Job that is sent by researcher

params_url str

URL where model parameters are uploaded

training_args dict

Arguments for training routine

dataset_id str

id of the dataset that is used for training

training bool

Declares whether training will be performed

model_args dict

Arguments to initialize training plan class

training_plan_url str

URL where TrainingPlan is available

training_plan_class str

Class name of the training plan

command str

Reply command string

aggregator_args dict

??

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

aggregator_args class-attribute
aggregator_args: dict
command class-attribute
command: str
dataset_id class-attribute
dataset_id: str
job_id class-attribute
job_id: str
model_args class-attribute
model_args: dict
params_url class-attribute
params_url: str
researcher_id class-attribute
researcher_id: str
round class-attribute
round: int
secagg_biprime_id class-attribute
secagg_biprime_id: str, type(None)
secagg_clipping_range class-attribute
secagg_clipping_range: int, type(None)
secagg_random class-attribute
secagg_random: float, type(None)
secagg_servkey_id class-attribute
secagg_servkey_id: str, type(None)
training class-attribute
training: bool
training_args class-attribute
training_args: dict
training_plan_class class-attribute
training_plan_class: str
training_plan_url class-attribute
training_plan_url: str

TrainingPlanStatusReply dataclass

Bases: Message

Describes a training plan approve status check message sent by the node

Attributes:

Name Type Description
researcher_id str

Id of the researcher that sends the request

node_id str

Node id that replys the request

job_id str

job id related to the experiment

succes str

True if the node process the request as expected, false if any execption occurs

approval_obligation

Approval mode for node. True, if training plan approval is enabled/required in the node for training.

is_approved

True, if the requested training plan is one of the approved training plan by the node

msg str

Message from node based on state of the reply

training_plan_url str

The training plan that has been checked for approval

command str

Reply command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

approval_obligation class-attribute
approval_obligation: bool
command class-attribute
command: str
job_id class-attribute
job_id: str
msg class-attribute
msg: str
node_id class-attribute
node_id: str
researcher_id class-attribute
researcher_id: str
status class-attribute
status: str
success class-attribute
success: bool
training_plan_url class-attribute
training_plan_url: str

TrainingPlanStatusRequest dataclass

Bases: Message

Describes a training plan approve status check message sent by the researcher.

Attributes:

Name Type Description
researcher_id str

Id of the researcher that sends the request

job_id str

Job id related to the experiment.

training_plan_url str

The training plan that is going to be checked for approval

command str

Request command string

Raises:

Type Description
FedbiomedMessageError

triggered if message's fields validation failed

Attributes

command class-attribute
command: str
job_id class-attribute
job_id: str
researcher_id class-attribute
researcher_id: str
training_plan_url class-attribute
training_plan_url: str

Functions

catch_dataclass_exception(cls)

Encapsulates the init() method of dataclass in order to transform the exceptions sent by the dataclass (TypeError) into our own exception (FedbiomedMessageError)

Parameters:

Name Type Description Default
cls Callable

Dataclass to validate

required
Source code in fedbiomed/common/message.py
def catch_dataclass_exception(cls: Callable):
    """Encapsulates the __init__() method of dataclass in order to transform the exceptions sent
    by the dataclass (TypeError) into our own exception (FedbiomedMessageError)

    Args:
        cls: Dataclass to validate
    """

    def __cde_init__(self: Any, *args: list, **kwargs: dict):
        """This is the __init__() replacement.

        Its purpose is to catch the TypeError created by the __init__
        method of the @dataclass decorator and replace this exception by  FedbiomedMessageError

        Raises:
          FedbiomedMessageError if number/type of arguments is wrong
        """

        try:
            self.__class__.__dict__['__initial_init__'](self, *args, **kwargs)

        except TypeError as e:
            # this is the error raised by dataclass if number of parameter is wrong
            _msg = ErrorNumbers.FB601.value + ": bad number of parameters: " + str(e)
            logger.error(_msg)
            raise FedbiomedMessageError(_msg)

    @functools.wraps(cls)
    def wrap(cls: Callable):
        """ Wrapper to the class given as parameter

        Class wrapping should keep some attributes (__doc__, etc) of the initial class or the API documentation tools
        will be mistaken

        """
        cls.__initial_init__ = cls.__init__
        setattr(cls, "__init__", __cde_init__)

        return cls

    return wrap(cls)