The marshal Module

The marshal module is used to serialize datathat is, convert data to and from character strings, so that they can be stored on file or sent over a network. Example 4-9 illustrates this.

The marshal module uses a simple self-describing data format. For each data item, the marshalled string contains a type code, followed by one or more type-specific fields. Integers are stored in little-endian order, strings are stored as length fields followed by the strings' contents (which can include null bytes), tuples are stored as length fields followed by the objects that make up each tuple, etc.

Example 4-9. Using the marshal Module to Serialize Data

File: marshal-example-1.py

import marshal

value = (
 "this is a string",
 [1, 2, 3, 4],
 ("more tuples", 1.0, 2.3, 4.5),
 "this is yet another string"
 )

data = marshal.dumps(value)

# intermediate format
print type(data), len(data)

print "-"*50
print repr(data)
print "-"*50

print marshal.loads(data)

 118
--------------------------------------------------
'(04000000s20000000this is a string
[04000000i01000000i02000000
i03000000i04000000(04000000
s13000000more tuplesf031.0f032.3f034.
5s32000000this is yet another string'
--------------------------------------------------
('this is a string', [1, 2, 3, 4], ('more tuples',
1.0, 2.3, 4.5), 'this is yet another string')

The marshal module can also handle code objects (it's used to store precompiled Python modules). Example 4-10 demonstrates.

Example 4-10. Using the marshal Module to Serialize Code

File: marshal-example-2.py

import marshal

script = """
print 'hello'
"""

code = compile(script, "

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net