EDN Format Reader and Writer
edn-format is a Python library that implements the Extensible Data Notation (EDN) format, providing functionalities to read (loads, loads_all) and write (dumps) EDN data, including support for custom tagged elements. The current version, 0.7.5, was released in November 2020, and the project is considered stable and actively maintained on GitHub, despite a less frequent release cadence.
Warnings
- gotcha The library, following EDN's rationale, aims to yield immutable Python data structures (e.g., tuples for lists, frozensets for sets, ImmutableDict for maps) where possible. This can be unexpected for Python developers accustomed to mutable lists and dictionaries.
- gotcha When serializing Python dictionaries, string keys will be dumped as EDN strings, not EDN keywords. To output EDN keywords for dictionary keys, you must explicitly use `edn_format.Keyword('your-key')` as the Python dictionary key.
- gotcha EDN is a human-readable data format, and implementations like `edn-format` may not offer the same performance characteristics (speed and memory usage) as highly optimized binary serialization formats or even standard JSON libraries for high-throughput data transfer scenarios. For wire protocols, alternatives like Cognitect Transit might be more suitable.
- gotcha While `edn-format` supports custom tagged literals, correctly implementing and registering reader/writer handlers for them can be complex and requires a good understanding of both the EDN specification and the library's extension mechanisms.
Install
-
pip install edn-format
Imports
- edn_format.loads
import edn_format edn_format.loads("[1 2 3]") - edn_format.dumps
import edn_format edn_format.dumps([1, 2, 3])
- edn_format.loads_all
import edn_format edn_format.loads_all("1 2 3") - edn_format.Keyword
import edn_format edn_format.Keyword("my-key") - edn_format.Char
import edn_format edn_format.Char("\n")
Quickstart
import edn_format
# Define some Python data
python_data = {
edn_format.Keyword('name'): 'Alice',
edn_format.Keyword('age'): 30,
edn_format.Keyword('tags'): {'python', 'edn'},
edn_format.Keyword('active?'): True,
edn_format.Keyword('notes'): edn_format.Char('\n') # Example of EDN char literal
}
# Dump Python data to EDN string
edn_string = edn_format.dumps(python_data, sort_keys=True, indent=2)
print("--- EDN Output ---")
print(edn_string)
# Expected output might look like:
# {
# :active? true,
# :age 30,
# :name "Alice",
# :notes \newline,
# :tags #{"edn" "python"}
# }
# Load EDN string back to Python data
edn_input = "{ :id 123 :items [\"apple\" \"banana\"] :metadata #myapp/custom {\"version\" \"1.0\"} }"
loaded_data = edn_format.loads(edn_input)
print("\n--- Loaded Python Data ---")
print(loaded_data)
# Example of accessing loaded data
# print(loaded_data[edn_format.Keyword('id')]) # 123
# print(loaded_data[edn_format.Keyword('items')]) # ['apple', 'banana']