Cobble: Create Python Data Objects
Cobble is a Python library designed for the easy creation of data objects. It automatically implements common methods such as `__eq__` and `__repr__`, simplifying the boilerplate typically associated with simple data-holding classes. The current version is 0.1.4, released on June 1, 2024, and it is actively maintained with a stable release cadence.
Warnings
- gotcha Mutable default arguments in `cobble.field(default=...)` can lead to unexpected shared state across instances. This is a common Python footgun, also applicable to `dataclasses` and `cobble`.
- gotcha Overriding `__init__` in a `cobble.data` class will prevent Cobble from automatically generating its own `__init__` method, potentially leading to uninitialized fields or `AttributeError` if not handled carefully.
- gotcha Accessing fields directly on a `cobble.data` class before instantiation (e.g., `MyClass.field_name`) will result in an `AttributeError` if the field is intended for instances.
Install
-
pip install cobble
Imports
- data
import cobble @cobble.data
- field
import cobble cobble.field()
- visitor
import cobble cobble.visitor(BaseClass)
Quickstart
import cobble
@cobble.data
class Song(object):
name = cobble.field()
artist = cobble.field()
album = cobble.field(default=None)
song = Song("MFEO", artist="Jack's Mannequin", album="Everything in Transit")
print(song)
@cobble.data
class Literal:
value = cobble.field()
@cobble.data
class Add:
left = cobble.field()
right = cobble.field()
class Evaluator(cobble.visitor(object)):
def visit_literal(self, literal):
return literal.value
def visit_add(self, add):
return self.visit(add.left) + self.visit(add.right)
expression = Add(Literal(2), Literal(4))
result = Evaluator().visit(expression)
print(f"Evaluation of {expression} is: {result}")