### Install sexpdata via pip Source: https://github.com/jd-boyd/sexpdata/blob/main/README.rst Install the package from PyPI using the pip command. ```bash pip install sexpdata ``` -------------------------------- ### sexp2json Command-Line Usage Source: https://context7.com/jd-boyd/sexpdata/llms.txt Examples of using the `sexp2json` command-line tool to convert S-expression files to JSON. Covers single file conversion, output to a file, setting recursion limits, and accessing help. ```bash # Convert single file to stdout sexp2json input.sexp # Convert to output file sexp2json input.sexp -o output.json # Handle deeply nested expressions with custom recursion limit sexp2json deeply-nested.sexp -l 5000 # Usage help sexp2json --help ``` -------------------------------- ### Release Commands Source: https://github.com/jd-boyd/sexpdata/blob/main/README.rst Standard commands for building and uploading a new release to PyPI. ```bash python -m build twine check dist/* git tag v1.0.x twine upload dist/* ``` -------------------------------- ### Load S-expressions from Files Source: https://context7.com/jd-boyd/sexpdata/llms.txt Use load to read S-expressions from file-like objects. ```python from sexpdata import load, dump import io # Load from file with open('config.sexp', 'r') as f: config = load(f) # Load from StringIO fp = io.StringIO('(settings (theme "dark") (font-size 14))') result = load(fp) print(result) # [Symbol('settings'), [Symbol('theme'), 'dark'], [Symbol('font-size'), 14]] ``` -------------------------------- ### Write S-expressions to Files Source: https://context7.com/jd-boyd/sexpdata/llms.txt Use dump to write Python objects as S-expressions to file-like objects. ```python from sexpdata import dump, Symbol import io # Write to file config = [Symbol('settings'), [Symbol('theme'), 'dark'], [Symbol('font-size'), 14]] with open('config.sexp', 'w') as f: dump(config, f) # Write to StringIO fp = io.StringIO() dump(('a', 'b'), fp, str_as='symbol') print(fp.getvalue()) # (a b) ``` -------------------------------- ### Access Lists with car and cdr Source: https://context7.com/jd-boyd/sexpdata/llms.txt Perform traditional Lisp-style list operations to retrieve the first element or the remainder of a list. ```python from sexpdata import car, cdr, loads, Symbol # car returns the first element expr = loads('(a b c)') print(car(expr)) # Symbol('a') # cdr returns the rest of the list print(cdr(expr)) # [Symbol('b'), Symbol('c')] # Works with dotted pairs dotted = loads('(a . b)') print(car(dotted)) # Symbol('a') print(cdr(dotted)) # Symbol('b') # cdr of single-element list single = loads('(a)') print(cdr(single)) # [] # cdr of dotted pair with list expr = loads('(a . (b c))') print(cdr(expr)) # [Symbol('b'), Symbol('c')] ``` -------------------------------- ### Control Delimiters Source: https://context7.com/jd-boyd/sexpdata/llms.txt Use Brackets or Parens classes to explicitly define output delimiters during serialization. ```python from sexpdata import Brackets, Parens, dumps # Use Brackets for square bracket output print(dumps(Brackets([1, 2, 3]))) # Output: [1 2 3] print(dumps(Brackets({'a': 1, 'b': 2}))) # Output: [:a 1 :b 2] # Use Parens to force parentheses (default behavior) print(dumps(Parens([1, 2, 3]))) # Output: (1 2 3) # Mix in nested structures print(dumps([0, Brackets([1, 2]), 3])) # Output: (0 [1 2] 3) # Override tuple_as='array' locally print(dumps((0, Parens((1, 2, 3)), 4), tuple_as='array')) # Output: [0 (1 2 3) 4] ``` -------------------------------- ### Extend Serialization with tosexp Source: https://context7.com/jd-boyd/sexpdata/llms.txt Register custom serialization logic for specific types or classes using the tosexp decorator. ```python import sexpdata from sexpdata import tosexp, dumps from collections import namedtuple # Define a custom Cons cell class class Cons(namedtuple('Cons', 'car cdr')): pass # Register custom serialization @sexpdata.tosexp.register(Cons) def _(obj, **kwds): return '({0} . {1})'.format( sexpdata.tosexp(obj.car, **kwds), sexpdata.tosexp(obj.cdr, **kwds) ) # Use custom type print(dumps(Cons(True, False))) # Output: (t . ()) # Create an association list alist = list(map(Cons, 'abc', range(3))) print(dumps(alist, str_as='symbol')) # Output: ((a . 0) (b . 1) (c . 2)) # Override built-in type serialization (e.g., float formatting) @sexpdata.tosexp.register(float) def _(obj, **kwds): return '{0:.2f}'.format(obj) import math print(dumps([math.pi, math.e])) # Output: (3.14 2.72) # Classes with __to_lisp_as__ method class Point: def __init__(self, x, y): self.x = x self.y = y def __to_lisp_as__(self): return [sexpdata.Symbol('point'), self.x, self.y] print(dumps(Point(10, 20))) # Output: (point 10 20) ``` -------------------------------- ### load - Load S-expression from File Source: https://context7.com/jd-boyd/sexpdata/llms.txt Reads and parses an S-expression from a file-like object. ```APIDOC ## load - Load S-expression from File ### Description Reads and parses an S-expression from a file-like object. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sexpdata import load, dump import io # Load from file with open('config.sexp', 'r') as f: config = load(f) # Load from StringIO fp = io.StringIO('(settings (theme "dark") (font-size 14))') result = load(fp) print(result) # [Symbol('settings'), [Symbol('theme'), 'dark'], [Symbol('font-size'), 14]] ``` ### Response #### Success Response (200) - **parsed_object** (object) - The parsed Python object representation of the S-expression from the file. ``` -------------------------------- ### Programmatic S-expression to JSON Conversion Source: https://context7.com/jd-boyd/sexpdata/llms.txt Shows how to use the `sexp2json` library programmatically to convert an S-expression string into a JSON-serializable Python data structure. ```python # Programmatic usage of sexp2json from sexp2json import sexp2json, tojsonable import sexpdata import io # Convert S-expression to JSON-serializable structure sexp = sexpdata.parse('(config (name "app") (port 8080))') json_data = tojsonable(sexp) print(json_data) # [['config', ['name', 'app'], ['port', 8080]]] ``` -------------------------------- ### Serialize Python Objects to S-expressions Source: https://context7.com/jd-boyd/sexpdata/llms.txt Use dumps to convert Python objects into S-expression strings with various formatting options. ```python from sexpdata import dumps, Symbol, Quoted, Brackets # Basic serialization print(dumps(['hello', 'world'])) # Output: ("hello" "world") # Serialize strings as symbols (unquoted) print(dumps(['a', 'b'], str_as='symbol')) # Output: (a b) # Serialize with Symbol objects print(dumps([Symbol('define'), Symbol('x'), 42])) # Output: (define x 42) # Serialize dictionaries as property lists print(dumps({'name': 'Alice', 'age': 30})) # Output: (:name "Alice" :age 30) # Serialize tuples as arrays (square brackets) print(dumps(('a', 'b'), tuple_as='array')) # Output: ["a" "b"] # Serialize quoted expressions print(dumps([Symbol('a'), Quoted(Symbol('b'))])) # Output: (a 'b) # Custom boolean/None representations print(dumps([None, True, False])) # Output: (() t ()) print(dumps([None, True, False], none_as='null', true_as='#t', false_as='#f')) # Output: (null #t #f) # Pretty printing with indentation data = [Symbol('defun'), Symbol('factorial'), [Symbol('n')], [Symbol('if'), [Symbol('<='), Symbol('n'), 1], 1, [Symbol('*'), Symbol('n'), [Symbol('factorial'), [Symbol('-'), Symbol('n'), 1]]]]] print(dumps(data, pretty_print=True, indent_as=' ')) # Output: # ( # defun # factorial # ( # n # ) # ... # ) # Force square brackets with Brackets wrapper print(dumps(Brackets([1, 2, 3]))) # Output: [1 2 3] ``` -------------------------------- ### Manage Lisp Symbols Source: https://context7.com/jd-boyd/sexpdata/llms.txt Create and manipulate Symbol objects, which are distinct from strings and hashable. ```python from sexpdata import Symbol, loads, dumps # Create symbols directly sym = Symbol('my-function') print(repr(sym)) # Symbol('my-function') print(str(sym)) # my-function # Access the symbol's string value print(sym.value()) # my-function # Symbols are hashable and can be dictionary keys d = {Symbol('key'): 'value', 'key': 'other'} print(len(d)) # 2 (Symbol('key') and 'key' are different) # Symbols with special characters are properly escaped print(dumps(Symbol('path join'))) # path\ join print(dumps(Symbol("path'quote"))) # path\'quote # Parse symbols back result = loads(r'path\ join') print(result) # Symbol('path join') ``` -------------------------------- ### Handling S-expression Parsing Errors Source: https://context7.com/jd-boyd/sexpdata/llms.txt Demonstrates how to catch and inspect various S-expression parsing errors, including UnterminatedString, ExpectClosingBracket, ExpectNothing, and ExpectSExp. Error objects provide position information for debugging. ```python from sexpdata import ( loads, parse, Position, SExpError, ExpectClosingBracket, ExpectNothing, ExpectSExp, UnterminatedString, InvalidEscape ) # Unterminated string error try: loads('"hello') except UnterminatedString as e: print(f"Error: {e}") print(f"Position: line {e.position.line}, column {e.position.column}") # Error: Unterminated string literal at line 1, column 1 # Position: line 1, column 1 # Missing closing bracket try: loads('(a b') except ExpectClosingBracket as e: print(f"Error: {e}") print(f"Position: {e.position}") # Error: Not enough closing brackets... # Position: line 1, column 1 # Too many closing brackets try: loads('(a b))') except ExpectNothing as e: print(f"Error: {e}") print(f"Position: line {e.position.line}, col {e.position.column}") # Error: Too many closing brackets... # Position: line 1, col 6 # Quote without expression try: loads("(foo)'") except ExpectSExp as e: print(f"Error: {e}") # Error: No s-exp is found after an apostrophe at line 1, column 6 # Multiline error position tracking multiline = """( (nested "unterminated""" try: loads(multiline) except UnterminatedString as e: print(f"Error at line {e.position.line}, column {e.position.column}") # Error at line 3, column 5 # Position object usage pos = Position(line=5, column=10, offset=42) print(str(pos)) # line 5, column 10 print(repr(pos)) # Position(line=5, column=10) ``` -------------------------------- ### Manage Quoted Expressions Source: https://context7.com/jd-boyd/sexpdata/llms.txt Work with quoted expressions prefixed with the ' character. ```python from sexpdata import Quoted, Symbol, loads, dumps # Create quoted expressions q = Quoted(Symbol('x')) print(repr(q)) # Quoted(Symbol('x')) # Dump quoted expressions print(dumps(Quoted(Symbol('x')))) # 'x print(dumps(Quoted([Symbol('a'), Symbol('b')]))) # '(a b) # Parse quoted expressions result = loads("'x") print(result) # Quoted(Symbol('x')) result = loads("(list 'a 'b)") print(result) # [Symbol('list'), Quoted(Symbol('a')), Quoted(Symbol('b'))] ``` -------------------------------- ### dump - Write S-expression to File Source: https://context7.com/jd-boyd/sexpdata/llms.txt Writes a Python object as an S-expression to a file-like object. ```APIDOC ## dump - Write S-expression to File ### Description Writes a Python object as an S-expression to a file-like object. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sexpdata import dump, Symbol import io # Write to file config = [Symbol('settings'), [Symbol('theme'), 'dark'], [Symbol('font-size'), 14]] with open('config.sexp', 'w') as f: dump(config, f) # Write to StringIO fp = io.StringIO() dump(('a', 'b'), fp, str_as='symbol') print(fp.getvalue()) # (a b) ``` ### Response #### Success Response (200) - **None** - This function writes to a file-like object and does not return a value. ``` -------------------------------- ### Parse and Serialize S-expressions Source: https://github.com/jd-boyd/sexpdata/blob/main/README.rst Use loads to parse an S-expression string into a Python list and dumps to serialize a list back into an S-expression string. ```python >>> from sexpdata import loads, dumps >>> loads('("a" "b")') ['a', 'b'] >>> print(dumps(['a', 'b'])) ("a" "b") ``` -------------------------------- ### Manage Quoted Strings Source: https://context7.com/jd-boyd/sexpdata/llms.txt Handle double-quoted strings with automatic escape sequence management. ```python from sexpdata import String, dumps # Create String objects s = String('hello\nworld') print(repr(s)) # String('hello\nworld') print(str(s)) # hello # world # Access the string value print(s.value()) # hello\nworld # Strings are hashable d = {String('a'): 1, Symbol('a'): 2, 'a': 3} print(len(d)) # 3 (all distinct) # Escape sequences are handled automatically print(dumps('line1\nline2')) # "line1\nline2" print(dumps('tab\there')) # "tab\there" print(dumps('quote"here')) # "quote\"here" ``` -------------------------------- ### dumps - Convert Python Object to S-expression String Source: https://context7.com/jd-boyd/sexpdata/llms.txt Converts a Python object to an S-expression string representation. Supports various options for controlling output format. ```APIDOC ## dumps - Convert Python Object to S-expression String ### Description Converts a Python object to an S-expression string representation. Supports various options for controlling output format. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sexpdata import dumps, Symbol, Quoted, Brackets # Basic serialization print(dumps(['hello', 'world'])) # Output: ("hello" "world") # Serialize strings as symbols (unquoted) print(dumps(['a', 'b'], str_as='symbol')) # Output: (a b) # Serialize with Symbol objects print(dumps([Symbol('define'), Symbol('x'), 42])) # Output: (define x 42) # Serialize dictionaries as property lists print(dumps({'name': 'Alice', 'age': 30})) # Output: (:name "Alice" :age 30) # Serialize tuples as arrays (square brackets) print(dumps(('a', 'b'), tuple_as='array')) # Output: ["a" "b"] # Serialize quoted expressions print(dumps([Symbol('a'), Quoted(Symbol('b'))])) # Output: (a 'b) # Custom boolean/None representations print(dumps([None, True, False])) # Output: (() t ()) print(dumps([None, True, False], none_as='null', true_as='#t', false_as='#f')) # Output: (null #t #f) # Pretty printing with indentation data = [Symbol('defun'), Symbol('factorial'), [Symbol('n')], [Symbol('if'), [Symbol('<='), Symbol('n'), 1], 1, [Symbol('*'), Symbol('n'), [Symbol('factorial'), [Symbol('-'), Symbol('n'), 1]]]]] print(dumps(data, pretty_print=True, indent_as=' ')) # Output: # ( # defun # factorial # ( # n # ) # ... # ) # Force square brackets with Brackets wrapper print(dumps(Brackets([1, 2, 3]))) # Output: [1 2 3] ``` ### Response #### Success Response (200) - **output_string** (string) - The S-expression string representation of the Python object. ``` -------------------------------- ### Parse Multiple S-expressions Source: https://context7.com/jd-boyd/sexpdata/llms.txt Use parse to return a list of all top-level S-expressions in a string. ```python from sexpdata import parse, Symbol # Parse returns a list of all expressions result = parse('(a b)') print(result) # [[Symbol('a'), Symbol('b')]] ``` -------------------------------- ### Parse S-expression Strings Source: https://context7.com/jd-boyd/sexpdata/llms.txt Use loads to convert S-expression strings into Python objects. Supports customization of symbols and comment characters. ```python from sexpdata import loads, Symbol, Quoted # Basic parsing - strings result = loads('("hello" "world")') print(result) # ['hello', 'world'] # Parsing symbols (unquoted identifiers) result = loads('(define x 42)') print(result) # [Symbol('define'), Symbol('x'), 42] # Parsing numbers result = loads('(1 2.5 -3.14 2E22)') print(result) # [1, 2.5, -3.14, 2e+22] # Parsing quoted expressions result = loads("(a 'b)") print(result) # [Symbol('a'), Quoted(Symbol('b'))] # Parsing nested lists result = loads('((a b) (c d))') print(result) # [[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]] # Parsing with comments (ignored) result = loads(''' ;; This is a comment (data "value") ; inline comment ''') print(result) # [Symbol('data'), 'value'] # Customizing nil/true/false symbols result = loads('nil') # [] (empty list by default) result = loads('t') # True result = loads('null', nil='null') # [] result = loads('#t', true='#t') # True result = loads('#f', false='#f') # False # Custom line comment character result = loads('(a b) # Python-style comment', line_comment='#') print(result) # [Symbol('a'), Symbol('b')] ``` -------------------------------- ### loads - Parse S-expression String Source: https://context7.com/jd-boyd/sexpdata/llms.txt Parses an S-expression string and returns the corresponding Python object. Supports customization of nil, true, false symbols and line comment characters. ```APIDOC ## loads - Parse S-expression String ### Description Parses an S-expression string and returns the corresponding Python object. Supports customization of nil, true, false symbols and line comment characters. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sexpdata import loads, Symbol, Quoted # Basic parsing - strings result = loads('("hello" "world")') print(result) # ['hello', 'world'] # Parsing symbols (unquoted identifiers) result = loads('(define x 42)') print(result) # [Symbol('define'), Symbol('x'), 42] # Parsing numbers result = loads('(1 2.5 -3.14 2E22)') print(result) # [1, 2.5, -3.14, 2e+22] # Parsing quoted expressions result = loads("(a 'b)") print(result) # [Symbol('a'), Quoted(Symbol('b'))] # Parsing nested lists result = loads('((a b) (c d))') print(result) # [[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]] # Parsing with comments (ignored) result = loads(''' ;; This is a comment (data "value") ; inline comment ''') print(result) # [Symbol('data'), 'value'] # Customizing nil/true/false symbols result = loads('nil') # [] (empty list by default) result = loads('t') # True result = loads('null', nil='null') # [] result = loads('#t', true='#t') # True result = loads('#f', false='#f') # False # Custom line comment character result = loads('(a b) # Python-style comment', line_comment='#') print(result) # [Symbol('a'), Symbol('b')] ``` ### Response #### Success Response (200) - **result** (object) - The parsed Python object representation of the S-expression. ``` -------------------------------- ### Parse S-expressions Source: https://context7.com/jd-boyd/sexpdata/llms.txt Basic usage of the parse function to convert S-expression strings into Python objects. ```python result = parse('a') print(result) # [Symbol('a')] # Parse with quoted expressions result = parse("(a '(b c))") print(result) # [[Symbol('a'), Quoted([Symbol('b'), Symbol('c')])]] ``` -------------------------------- ### parse - Parse Multiple S-expressions Source: https://context7.com/jd-boyd/sexpdata/llms.txt Lower-level function that parses a string and returns a list of all top-level S-expressions found. ```APIDOC ## parse - Parse Multiple S-expressions ### Description Lower-level function that parses a string and returns a list of all top-level S-expressions found. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sexpdata import parse, Symbol # Parse returns a list of all expressions result = parse('(a b)') print(result) # [[Symbol('a'), Symbol('b')]] ``` ### Response #### Success Response (200) - **parsed_expressions** (list) - A list containing all top-level S-expressions found in the input string. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.