Marshal — internal serialization of Python objects

The Marshal module exists primarily to support reading and writing “pseudo-compiled” code for Python modules in .pyc files. This module does not support all types of Python objects.

The following types are supported: booleans, integers, floating point numbers, complex numbers, strings, bytes, byte arrays, tuples, lists, sets, freezes, dictionaries and code objects, where it should be understood that tuples, lists, sets, freezes, and dictionaries are supported only as long as the values ​​they contain are supported. The singletones None, Ellipsis and StopItate can also be marshaled and parsed.

Functions :

  1. Marshal.version:
    Specifies the format used by the module.
    • Version 0 — Historical format
    • Version 1 — strips interned strings
    • Version 2 — uses binary format for floating point numbers
    • Version 3 — Object Instance and Recursion Support
    • Version 4 — Current version
  2. marshal.dumps (value [, version]):
    The function returns a byte object that would have been written to the file by dump (value, file). The version argument specifies the data format that the dump should use. A ValueError is thrown if the value is (or contains an object that has) an unsupported type.

    example

    # Python code to demonstrate serialization

    import marshal

     

    data = { 12 : `twelve` , `feep` : list ( `ciao` ), 1.23 : 4 + 5j

    ( 1 , 2 , 3 ): u `wer` }

    bytes = marshal.dumps (data)

     

    print bytes

    Exit

     {tfeep [tctitatog®Gáz®ó? y @@ ittwelve (iiiuwer0} 
  3. marshal.loads (bytes):
    This function can reverse engineer data by converting a byte-like object to a value. EOFError, ValueError, or TypeError are raised if no value is found.

    example

    # Python code to demonstrate deserialization

    import marshal

      

    data = { 12 : `twelve` , `feep` : list ( `ciao` ), 1.23 : 4 + 5j

      ( 1 , 2 , 3 ): u `wer` }

    bytes = marshal.dumps (data)

    redata = marshal.loads (bytes)

      

    print redata

    Exit

     {12: `twelve`, 1.23: (4 + 5j ), `feep`: [` c`, `i`,` a`, `o`], (1, 2, 3): u`wer`} 
  4. marshal.dump (value, file [, version]):
    This function is used to write a value of a supported type to an open writeable binary f isle. A ValueError exception is thrown if the value is of an unsupported type.
  5. marshal.load (file):
    This function reads one value from an open readable binary file and returns it. EOFError, ValueError, or TypeError are raised if the value is not readable.

This article is provided by Aditi Gupta . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic discussed above.