mpacklog — Log dictionaries to file using MessagePack  v2.1.0
serialize.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2022 Stéphane Caron
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 
18 
19 def serialize(obj):
20  """!
21  Serialize an object for message packing.
22 
23  @param obj Object to serialize.
24 
25  @returns Serialized object.
26 
27  @note Calling the numpy conversion is much faster than the default list
28  constructor:
29 
30  @code{python}
31  In [1]: x = random.random(6)
32 
33  In [2]: %timeit list(x)
34  789 ns ± 5.79 ns per loop (mean ± std. dev. of 7 runs, 1e6 loops each)
35 
36  In [3]: %timeit x.tolist()
37  117 ns ± 0.865 ns per loop (mean ± std. dev. of 7 runs, 1e7 loops each)
38  @endcode
39  """
40  if hasattr(obj, "tolist"): # numpy.ndarray
41  return obj.tolist()
42  elif hasattr(obj, "np"): # pinocchio.SE3
43  return obj.np.tolist()
44  elif hasattr(obj, "serialize"): # more complex objects
45  return obj.serialize()
46  return obj
mpacklog.mpacklog.python.serialize.serialize
def serialize(obj)
Serialize an object for message packing.
Definition: serialize.py:19