Serialize input `data` to a target format. Input `data` can be any supported Python type, including :class:`list`, :class:`dict` or any serializable Python object. Serializable python objects are class extending :class:`~wolframclient.serializers.serializable.WLSerializable` and
(data, stream=None, target_format=DEFAULT_FORMAT, **options)
| 15 | |
| 16 | |
| 17 | def export(data, stream=None, target_format=DEFAULT_FORMAT, **options): |
| 18 | """ Serialize input `data` to a target format. |
| 19 | |
| 20 | Input `data` can be any supported Python type, including :class:`list`, :class:`dict` or any serializable Python |
| 21 | object. |
| 22 | |
| 23 | Serializable python objects are class extending :class:`~wolframclient.serializers.serializable.WLSerializable` and |
| 24 | types declared in an encoder. |
| 25 | |
| 26 | The default format is :wl:`InputForm` string:: |
| 27 | |
| 28 | >>> export(wl.Range(3)) |
| 29 | b'Range[3]' |
| 30 | |
| 31 | Specify WXF format by setting `target_format`:: |
| 32 | |
| 33 | >>> export([1,2,3], target_format='wxf') |
| 34 | b'8:f\x03s\x04ListC\x01C\x02C\x03' |
| 35 | |
| 36 | .. note :: WXF is a binary format for serializing Wolfram Language expression. Consult the |
| 37 | `format specifications <https://reference.wolfram.com/language/tutorial/WXFFormatDescription.html>`_ for in |
| 38 | depth format description. |
| 39 | |
| 40 | WXF byte arrays are deserialized with :func:`~wolframclient.deserializers.binary_deserialize`:: |
| 41 | |
| 42 | >>> wxf = export([1,2,3], target_format='wxf') |
| 43 | >>> binary_deserialize(wxf) |
| 44 | [1, 2, 3] |
| 45 | |
| 46 | If `stream` is specified with a string, it is interpreted as a file path and the serialized form is written directly |
| 47 | to the specified file. The file is opened and closed automatically:: |
| 48 | |
| 49 | >>> export([1, 2, 3], stream='file.wl') |
| 50 | 'file.wl' |
| 51 | |
| 52 | If `stream` is specified with an output stream, the serialization bytes are written to it. |
| 53 | |
| 54 | Any object that implements a `write` method, e.g. :data:`file`, :class:`io.BytesIO` or :class:`io.StringIO`, is a |
| 55 | valid value for the `stream` named parameter:: |
| 56 | |
| 57 | >>> with open('file.wl', 'wb') as f: |
| 58 | ... export([1, 2, 3], stream=f) |
| 59 | ... |
| 60 | <open file 'file.wl', mode 'wb' at 0x10a4f01e0> |
| 61 | |
| 62 | """ |
| 63 | if not target_format in available_formats: |
| 64 | raise ValueError( |
| 65 | "Invalid export format %s. Choices are: %s" |
| 66 | % (target_format, ", ".join(available_formats.keys())) |
| 67 | ) |
| 68 | return available_formats[target_format](**options).export(data, stream=stream) |