marshal — Serialização interna de objetos Python


Este módulo contém funções que podem ler e gravar valores Python em formato binário. O formato é específico para Python, mas independente dos problemas de arquitetura da máquina (por exemplo, você pode gravar um valor Python em um arquivo em um PC, transportar o arquivo para um Sun e lê-lo de volta lá). Os detalhes do formato não são documentados propositalmente; ele pode mudar entre as versões do Python (embora raramente mude). [1]

This is not a general “persistence” module. For general persistence and transfer of Python objects through RPC calls, see the modules pickle and shelve. The marshal module exists mainly to support reading and writing the “pseudo-compiled” code for Python modules of .pyc files. Therefore, the Python maintainers reserve the right to modify the marshal format in backward incompatible ways should the need arise. The format of code objects is not compatible between Python versions, even if the version of the format is the same. De-serializing a code object in the incorrect Python version has undefined behavior. If you’re serializing and de-serializing Python objects, use the pickle module instead – the performance is comparable, version independence is guaranteed, and pickle supports a substantially wider range of objects than marshal.

Aviso

O módulo marshal não se destina a ser seguro contra dados errôneos ou construídos de forma maliciosa. Nunca faça o unmarshalling de dados recebidos de uma fonte não confiável ou não autenticada.

Not all Python object types are supported; in general, only objects whose value is independent from a particular invocation of Python can be written and read by this module. The following types are supported: booleans, integers, floating point numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets, frozensets, dictionaries, and code objects (if allow_code is true), 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. For format version lower than 3, recursive lists, sets and dictionaries cannot be written (see below).

Existem funções que leem/gravam arquivos, bem como funções que operam em objetos byte ou similares.

O módulo define estas funções:

marshal.dump(value, file, version=version, /, *, allow_code=True)

Grava o valor no arquivo aberto. O valor deve ser um tipo compatível. O arquivo deve ser arquivo binário gravável.

If the value has (or contains an object that has) an unsupported type, a ValueError exception is raised — but garbage data will also be written to the file. The object will not be properly read back by load(). Code objects are only supported if allow_code is true.

O argumento version indica o formato de dados que o dump deve usar (veja abaixo).

Levanta um evento de auditoria marshal.dumps com argumentos value, version.

Alterado na versão 3.13: Added the allow_code parameter.

marshal.load(file, /, *, allow_code=True)

Read one value from the open file and return it. If no valid value is read (e.g. because the data has a different Python version’s incompatible marshal format), raise EOFError, ValueError or TypeError. Code objects are only supported if allow_code is true. The file must be a readable binary file.

Levanta um evento de auditoria marshal.load com nenhum argumento.

Nota

Se um objeto contendo um tipo não suportado foi empacotado com dump(), load() irá substituir None pelo tipo não empacotável.

Alterado na versão 3.10: Esta chamada costumava levantar um evento de auditoria code.__new__ para cada objeto código. Agora, ele levanta um único evento marshal.load para toda a operação de carregamento.

Alterado na versão 3.13: Added the allow_code parameter.

marshal.dumps(value, version=version, /, *, allow_code=True)

Return the bytes object that would be written to a file by dump(value, file). The value must be a supported type. Raise a ValueError exception if value has (or contains an object that has) an unsupported type. Code objects are only supported if allow_code is true.

O argumento version indica o formato de dados que dumps deve usar (veja abaixo).

Levanta um evento de auditoria marshal.dumps com argumentos value, version.

Alterado na versão 3.13: Added the allow_code parameter.

marshal.loads(bytes, /, *, allow_code=True)

Convert the bytes-like object to a value. If no valid value is found, raise EOFError, ValueError or TypeError. Code objects are only supported if allow_code is true. Extra bytes in the input are ignored.

Levanta um evento de auditoria marshal.loads com argumento bytes.

Alterado na versão 3.10: Esta chamada costumava levantar um evento de auditoria code.__new__ para cada objeto código. Agora, ele levanta um único evento marshal.loads para toda a operação de carregamento.

Alterado na versão 3.13: Added the allow_code parameter.

Além disso, as seguintes constantes são definidas:

marshal.version

Indica o formato que o módulo usa. A versão 0 é o formato histórico, a versão 1 compartilha strings internas e a versão 2 usa um formato binário para números de ponto flutuante. A versão 3 adiciona suporte para instanciação e recursão de objetos. A versão atual é 4.

Notas de rodapé