Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Object Serialization with Inheritance in Java
Next article icon

marshal — Internal Python object serialization

Last Updated : 05 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Serializing a data means converting it into a string of bytes and later reconstructing it from such a string. If the data is composed entirely of fundamental Python objects, the fastest way to serialize the data is by using marshal module (For user defined classes, Pickle should be preferred). Marshal module contains functions that can read and write Python values in a binary format. The marshal module exists mainly to support reading and writing the “pseudo-compiled” code for Python modules of .pyc files. This module doesn’t support all Python object types. The following types are supported: booleans, integers, floating point numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets, frozensets, dictionaries, and code objects, where it should be understood that tuples, lists, sets, frozensets and dictionaries are only supported as long as the values contained therein are themselves supported. The singletons None, Ellipsis and StopIteration can also be marshalled and unmarshalled. Functions : 

  • marshal.version : It indicates the format used by the module.
    • Version 0 - Historical format
    • Version 1 - Shares interned strings
    • Version 2 - Uses a binary format for floating point numbers
    • Version 3 - Support for object instancing and recursion
    • Version 4 - Current Version
  • marshal.dumps(value[, version]) : The function returns the bytes object that would be written to a file by dump(value, file). The version argument indicates the data format that dumps should use. A ValueError exception is raised if the value has (or contains an object that has) an unsupported type. Example 
Python3
# 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) 

Output

{tfeep[tctitatog®Gáz®ó?y@@ittwelve(iiiuwer0}
  • marshal.loads(bytes) : This function can reconstruct the data by converting the bytes-like object to a value. EOFError, ValueError or TypeError is raised if no value is found. Example 
Python3
# Python code to demonstrate de-serialization 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) 

Output

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


Next Article
Object Serialization with Inheritance in Java

A

Aditi Gupta
Improve
Article Tags :
  • Misc
  • Python
  • Python-Library
Practice Tags :
  • Misc
  • python

Similar Reads

  • pickle — Python object serialization
    Python is a widely used general-purpose, high-level programming language. In this article, we will learn about pickling and unpickling in Python using the pickle module. The Python Pickle ModuleThe pickle module is used for implementing binary protocols for serializing and de-serializing a Python ob
    9 min read
  • Object Serialization with Inheritance in Java
    Prerequisite: Serialization, Inheritance Serialization is a mechanism of converting the state of an object into a byte stream. The byte array can be the class, version, and internal state of the object. Deserialization is the reverse process where the byte stream is used to recreate the actual Java
    6 min read
  • Convert Object to String in Python
    Python provides built-in type conversion functions to easily transform one data type into another. This article explores the process of converting objects into strings which is a basic aspect of Python programming. Since every element in Python is an object, we can use the built-in str() and repr()
    2 min read
  • Serialize Python dictionary to XML
    XML is a markup language that is designed to transport data. It was made while keeping it self descriptive in mind. Syntax of XML is similar to HTML other than the fact that the tags in XML aren't pre-defined. This allows for data to be stored between custom tags where the tag contains details about
    5 min read
  • How to find size of an object in Python?
    In python, the usage of sys.getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself. Note: Only the memory consumption directly attributed t
    2 min read
  • Byte Objects vs String in Python
    In Python 2, both str and bytes are the same typeByte objects whereas in Python 3 Byte objects, defined in Python 3 are "sequence of bytes" and similar to "unicode" objects from Python 2. In this article, we will see the difference between byte objects and strings in Python and also will look at how
    3 min read
  • Modules available for Serialization and Deserialization in Python
    Python provides three different modules which allow us to serialize and deserialize objects :   Marshal ModulePickle ModuleJSON Module 1. Marshal Module: It is the oldest module among these three. It is mainly used to read and write the compiled byte code of Python modules. Even we can use marshal t
    3 min read
  • Deserialize JSON to Object in Python
    Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module
    2 min read
  • Object Interning In Python
    Object interning is a technique used in Python to optimize memory usage and improve performance by reusing immutable objects instead of creating new instances. It is particularly useful for strings, integers and user-defined objects. By interning objects, Python can store only one copy of each disti
    3 min read
  • Python - Convert Dictionary Object into String
    In Python, there are situations where we need to convert a dictionary into a string format. For example, given the dictionary {'a' : 1, 'b' : 2} the objective is to convert it into a string like "{'a' : 1, 'b' : 2}". Let's discuss different methods to achieve this: Using strThe simplest way to conve
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences