Cons Python Library
The `cons` library for Python provides an implementation of Lisp/Scheme-like cons cells, aiming to emulate their semantics while integrating with Python's built-in sequence types like lists and tuples. It facilitates functional programming patterns by allowing the construction and deconstruction of pairs. The library is actively maintained, with its current version being 0.4.7, and receives updates that include dependency bumps and Python version compatibility improvements.
Warnings
- breaking Python 3.7 support was deprecated in version 0.4.6. Users on Python 3.7 or older must upgrade their Python interpreter to at least 3.9 to use newer versions of `cons`.
- gotcha Attempting to call `car()` or `cdr()` on an empty Python sequence (e.g., `[]`, `()`) will raise a `ConsError`, as these are not considered valid `cons` pairs within the library's Scheme-like semantics.
- gotcha By default, `str` types are not treated as `cons`-pairs for `car`/`cdr` operations, even though they are Python sequences. Calling `cons("a", "string")` will produce a `ConsPair` object, but `car("string")` would raise `ConsError`.
Install
-
pip install cons
Imports
- cons
from cons import cons
- car
from cons import car
- cdr
from cons import cdr
Quickstart
from cons import cons, car, cdr
# Create cons cells with different sequence types
my_list_cons = cons(1, [2, 3])
my_tuple_cons = cons('a', ('b', 'c'))
my_none_cons = cons(42, None) # None acts like 'nil' in some Lisps
print(f"List cons: {my_list_cons}")
print(f"Tuple cons: {my_tuple_cons}")
print(f"None cons: {my_none_cons}")
# Accessing the head (car) and tail (cdr) of a cons cell
print(f"Car of list cons: {car(my_list_cons)}") # Output: 1
print(f"Cdr of list cons: {cdr(my_list_cons)}") # Output: [2, 3]
# cons also works with dictionaries or other iterables
from collections import OrderedDict
my_ordereddict_cons = cons(('key', 'value'), OrderedDict())
print(f"OrderedDict cons: {my_ordereddict_cons}")