Skip to content

[pynest] Better algoritm for serialize data #3698

@babsey

Description

@babsey

The algoritm of the serialize_data here is not clean:

def serialize_data(data):
"""Serialize data for JSON.
Parameters
----------
data : any
Returns
-------
data_serialized : str, int, float, list, dict
Data can be encoded to JSON
"""
if isinstance(data, (numpy.ndarray, NodeCollection)):
return data.tolist()
if isinstance(data, (numpy.integer)):
return int(data)
elif isinstance(data, SynapseCollection):
# Get full information from SynapseCollection
return serialize_data(data.get())
elif isinstance(data, kernel.SLILiteral):
# Get name of SLILiteral.
return data.name
elif isinstance(data, (list, tuple)):
return [serialize_data(d) for d in data]
elif isinstance(data, dict):
return dict([(key, serialize_data(value)) for key, value in data.items()])
return data

According to some suggestions online:

I would suggest to change the algorithm of this function to

def serialize_data(data):
    ...

    match data:
        case numpy.integer():
            return int(data)
        case numpy.floating():
            return float(data)
        case numpy.bool_():
            return bool(data)
        case numpy.ndarray() | NodeCollection():
            return serialize_data(data.tolist())
        case SynapseCollection():
            return serialize_data(data.get())
        case list() | tuple():
            return [serialize_data(d) for d in data]
        case dict():
            return {
                serialize_data(key): serialize_data(value)
                for key, value in data.items()
            }
    return data

Let's hear your thoughts on this idea.

Metadata

Metadata

Assignees

Labels

S: NormalHandle this with default priorityT: EnhancementNew functionality, model or documentation

Type

No type

Projects

Status

To do

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions