All Courses

Python Data Persistence - Marshal Module

Neha Kumawat

3 years ago

Marshal module is used by Python itself for Python’s internal object serialization to support reading/writing operations on compiled versions of Python modules (.pyc files). Marshal module's Object serialization features are the same as the pickle module.
The data format used by the marshal module is not compatible with Python versions. Therefore, a compiled Python script (.pyc file) of one version will probably not work for another.
For reading and writing marshalled objects from / to file marshal module defined load() and dump() functions.
       
Recommended Blogs for you :  Why pickling is important? 

dump() Function

This function is used to writes a byte representation of a Python object to a file with write permission.
Syntax : 
marshal.dump(value, file[, version])
Where ,
  • value must be a supported type.
  • The file must be a writable binary file.
  • version argument indicates the data format
If the value has an unsupported type then a ValueError exception is raised.

load() Function

This function reads one value(byte data) from an open binary file and returns the converted Python object.
Syntax :
marshal.load(file)
Where,
  •   The file must be a readable binary file.  
  If no value is read. then EOFError, ValueError or TypeError is raised.

compile() Function

The code uses the built-in compile() function which returns the python code object from the source 
Syntax :
compile(source, filename, mode, flag, dont_inherit, optimize) 
Where,
  • source -. can be a String, a Bytes object, or an AST object.
  • filename - The name of the file
  • mode -  exec or eval or single.
  • flag (optional) - How to compile the source object. Default 0.
  • dont_inherit (optional) - How to compile the source object. Default False.
  • optimize (optional) - optimization level of compiler. Default -1.
The mode parameter is:
  • ‘exec’ if the source contains a sequence of statements,
  •  ‘eval’ if there is a single expression 
  • ‘single’ if it contains a single interactive statement.
The compile code object is stored in a .pyc file using dump() function.
The following program shows the use of dump() and load() functions.

import marshal
script = """
a=10
b=20
print ('addition=',a+b)
"""
code = compile(script, "script", "exec")
f=open("a.pyc","wb")
marshal.dump(code, f)
f.close()
The load() function is used to deserialize the object from .pyc file. Since it returns a python code object, it can be run using exec() function or another built-in function.

import marshal
f=open("a.pyc","rb")
data=marshal.load(f)
exec (data)
     
Recommended Course for you :
      
Recommended Blogs for you :

Submit Review