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.
Common errors
-
ModuleNotFoundError: No module named 'cobble'
cause The 'cobble' library is not installed in the current Python environment.fixpip install cobble -
AttributeError: module 'cobble' has no attribute 'date'
cause The developer attempted to use a non-existent attribute 'date' (a common typo) instead of the correct decorator '@cobble.data' or another valid attribute within the 'cobble' module.fixCorrect the attribute name to the intended one, for example, change 'cobble.date' to 'cobble.data'. -
TypeError: cobble.field() got an unexpected keyword argument 'value'
cause The 'cobble.field()' function was called with a keyword argument that it does not recognize or support. For basic field declarations, 'cobble.field()' often takes no arguments or specific ones like 'default'.fixConsult the 'cobble' library documentation for the correct arguments accepted by 'cobble.field()', ensuring only valid keyword arguments (e.g., 'default') are used.
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}")