sexpdata
raw JSON → 1.0.2 verified Fri May 01 auth: no python
A simple S-expression parser for Python, supporting both parsing and serialization of S-expressions. Current version is 1.0.2, released January 2023. Development is active but releases are infrequent.
pip install sexpdata Common errors
error AttributeError: module 'sexpdata' has no attribute 'loads' ↓
cause Importing incorrectly (e.g., import sexpdata then sexpdata.loads). Actually loads is a top-level function; you must import it directly.
fix
Use: from sexpdata import loads
error ValueError: malformed S-expression at line 1 ↓
cause Input string is not properly formatted S-expression (e.g., missing closing parenthesis, stray characters).
fix
Ensure the input is valid S-expression. Validate with a validator or use a try/except block.
error TypeError: expected string or bytes-like object ↓
cause Passing a non-string (e.g., integer) to loads().
fix
Convert the argument to str: loads(str(my_var))
Warnings
gotcha sexpdata does not handle nil consistently; nil is parsed as Symbol('nil'), not Python's None. Comparison with None will fail. Use Symbol('nil') or check with .lower() if needed. ↓
fix Check for Symbol('nil') explicitly: from sexpdata import Symbol; if val == Symbol('nil'): ...
gotcha Parsing returns a list for the top-level S-expression, not a single element. A single atom like '42' will return a list containing the atom: [42]. This is different from some other parsers. ↓
fix If expecting a single atom, index into the result: parsed[0].
Imports
- loads wrong
import sexpdata; sexpdata.loads()correctfrom sexpdata import loads - dumps wrong
import sexpdata; sexpdata.dumps()correctfrom sexpdata import dumps
Quickstart
from sexpdata import loads, dumps
sexp_str = '(foo (bar 1 2) "string" nil)'
parsed = loads(sexp_str)
print(parsed) # Output: [Symbol('foo'), [Symbol('bar'), 1, 2], 'string', Symbol('nil')]
# Serialize back
sexp_out = dumps(parsed)
print(sexp_out) # Output: (foo (bar 1 2) "string" nil)