i2
Function signatures as data you can read, edit and combine, plus the wrappers, decorators and pipelines built on them. Where the standard library gives you a read-only inspect.Signature and functools.wraps, i2 gives you signatures you can rename, merge and apply as decorators, and wrappers that keep the input and output transformations in separate layers instead of a hand-written closure. It is the layer under dol, meshed and front: when they adapt one function's interface to another's, i2 does the work.
pip install i2
Pure Python, no required dependencies. Documentation.
For AI agents
i2 ships tooling for coding agents. If you are one, start here.
Skills (Agent Skills format), for any agent host.
| Skill |
Use it to |
i2-castgraph |
routing data through a graph of type/representation conversions with i2.castgraph's TransformationGraph — register pairwise transformers |
i2-multi-object |
composing and combining a fixed collection of functions |
i2-sig-arithmetic |
building, merging, and editing function signatures with i2's Sig — signature "+/-" arithmetic |
i2-signatures |
introspecting function signatures and binding call arguments to parameter names with i2's Sig class — turning an arbitrary |
i2-wrapper |
wrapping functions to transform their interface |
The documentation, machine-readable: llms.txt indexes every page; i2.md is the whole documentation in one file; every page has a .md twin; objects.inv maps symbols to URLs. The full list, with install lines, is on the site's For AI agents page.
If you identify as a dinosaur, the rest of this README is written for you, starting at Key Modules Overview.
Quick start
The smallest useful thing: read, edit and re-apply a function's signature with Sig. Note that applying a Sig rewrites the function's signature in place and returns the same function; use i2.wrap when you want a new one.
from i2 import Sig
def f(a, b=2, *, c=3):
return a + b * c
Sig(f) # <Sig (a, b=2, *, c=3)>
Sig(f).names # ['a', 'b', 'c']
g = Sig(f).ch_names(a="x")(f) # f itself, with its signature rewritten (g is f)
Sig(g) # <Sig (x, b=2, *, c=3)>
g(1) # 7
Change what goes in and what comes out of a function without touching it, or chain functions into one:
from i2 import Wrap, Pipe
add = lambda x, y: x + y
add_as_text = Wrap(add, egress=str)
add_as_text(1, 2) # '3'
clean = Pipe(str.strip, str.upper)
clean(" hello ") # 'HELLO'
What is in the box
i2 is a toolbox, and most people need one or two of its modules:
| Module |
What it gives you |
i2.signatures |
Sig: a signature you can introspect, add, subtract, rename and apply as a decorator. The core of the package. |
i2.wrapper |
Wrap, wrap, Ingress: change a function's inputs, outputs and signature in separate, composable layers. |
i2.deco |
ready-made decorators: preprocess, postprocess, double_up_as_factory, FuncFactory. |
i2.multi_object |
work with a fixed set of functions as one: Pipe, FuncFanout, MultiFunc, ParallelFuncs. |
i2.castgraph |
route a value through a graph of conversions (a path to a loaded object, text to a dict) with the cheapest path picked for you. |
i2.routing_forest |
nested if/then logic as a data structure you can compose and reuse. |
i2.util |
small helpers: name_of_obj, lazyprop, imdict, sentinels, identity and constant functions. |
The sections below cover the main ones with examples. The flat, single-file view of the whole documentation is i2.md.
Key Modules Overview
i2.castgraph - Type/Kind-Based Transformation Graphs
castgraph provides a graph-based system for organizing transformations between different data representations ("kinds"). It routes objects through multi-hop conversion paths, selecting the optimal route based on cost.
The castgraph tool addresses the common friction point in software design where a function requires a specific data type or format, but the user possesses related data in a different, interchangeable representation (e.g., a file path instead of a loaded object). Inspired by Postel's Law ("be liberal in what you accept"), the core problem is how to make interfaces highly flexible and accommodating of diverse inputs—eliminating tedious data preparation boilerplate for the user—while simultaneously adhering to the principle that "explicit is better than implicit" by keeping complex conversion logic out of the main application code; i2.castgraph solves this by providing a dedicated, cost-aware graph system to organize and execute necessary multi-hop transformations dynamically, effectively acting as an intelligent input adapter.
Read me in the castgraph dev notes.
Basic Usage (Type-Based):
from i2.castgraph import TransformationGraph
graph = TransformationGraph()
# Register transformations between types
@graph.register_edge(str, float)
def str_to_float(s, ctx):
return float(s)
@graph.register_edge(float, int)
def float_to_int(f, ctx):
return int(f)
# Automatically routes str -> float -> int
result = graph.transform("42.7", int)
assert result == 42
Advanced Usage (Kind-Based):
# Define custom "kinds" (not just types)
graph.add_node('json_string', isa=lambda x: isinstance(x, str) and x.startswith('{'))
graph.add_node('config_dict', isa=lambda x: isinstance(x, dict))
@graph.register_edge('json_string', 'config_dict')
def parse_json(text, ctx):
import json
return json.loads(text)
# Transform with automatic kind detection
result = graph.transform('{"key": "value"}', 'config_dict', from_kind='json_string')
Key Features:
- Multi-hop routing with cost-based path selection
- Support for arbitrary hashable kinds (types, strings, custom markers)
- Pluggable kind detection with predicates
- Context propagation for dependency injection
- MRO-aware fallback for type hierarchies
i2.signatures - Function Signature Manipulation
signatures provides a calculus for working with function signatures - introspecting, merging, and modifying them programmatically.
Signature Introspection:
from i2.signatures import Sig
def func(z, a: float = 1.0, /, b=2, *, c: int = 3):
pass
sig = Sig(func)
print(sig.names) # ['z', 'a', 'b', 'c']
print(sig.defaults) # {'a': 1.0, 'b': 2, 'c': 3}
print(sig.annotations) # {'a': <class 'float'>, 'c': <class 'int'>}
Signature Construction:
# From function
sig1 = Sig(lambda x, y: x + y)
# From list of names
sig2 = Sig(['a', 'b', 'c'])
# From string
sig3 = Sig('x y z')
# All create callable Signature objects
print(sig2) # <Sig (a, b, c)>
Signature Merging:
def foo(x, y=1): pass
def bar(z: int, *, w=2): pass
# Combine signatures
combined = Sig(foo) + Sig(bar)
print(combined) # <Sig (x, y=1, z: int, w=2)>
Decorating with Signatures:
# Give a function a specific signature
@Sig('a b c')
def func(*args, **kwargs):
print(f"Called with: {args}, {kwargs}")
# Now func has signature (a, b, c)
func(1, 2, 3) # Works as expected
Key Features:
- Extract parameter names, kinds, defaults, and annotations
- Merge multiple signatures flexibly
- Apply signatures as decorators
- Support for all parameter kinds (positional-only, keyword-only, VAR_POSITIONAL, VAR_KEYWORD)
- Signature algebra for composing function interfaces
i2.wrapper - Ingress/Egress Function Wrapping
wrapper provides the Wrap class for transforming function inputs and outputs through composable ingress/egress layers.
Basic Wrapping:
from i2.wrapper import Wrap
def add(x, y):
return x + y
# Transform inputs before function, outputs after
wrapped = Wrap(
add,
ingress=lambda x, y: ((x * 2, y * 2), {}), # Double inputs; returns (args, kwargs)
egress=lambda result: result / 2 # Halve output
)
result = wrapped(3, 4) # (3*2 + 4*2) / 2 = 7
assert result == 7
Signature Transformation:
from i2.wrapper import Ingress, wrap
def process(data: dict):
return data['value']
# Change signature: accept 'x' instead of 'data'
ingress = Ingress(
inner_sig=process,
outer_sig='x',
kwargs_trans=lambda outer_kwargs: {'data': {'value': outer_kwargs['x']}},
)
new_func = wrap(process, ingress=ingress)
result = new_func(42) # Calls process({'value': 42})
assert result == 42
The Wrap Flow:
*outer_args, **outer_kwargs
↓
[ingress] - transform inputs
↓
*inner_args, **inner_kwargs
↓
[func] - original function
↓
func_output
↓
[egress] - transform outputs
↓
final_output
Key Features:
- Separate ingress (input transformation) and egress (output transformation)
- Signature-aware argument mapping
- Composable wrapper layers
- Supports partial application and argument reordering
- Clean separation of concerns for cross-cutting functionality
i2.routing_forest - Conditional Logic as Data Structures
routing_forest lets you express nested if/then conditions as composable, reusable tree structures instead of tangled code.
Basic Routing:
from i2.routing_forest import RoutingForest, CondNode, FinalNode
# Define routing logic as a forest
router = RoutingForest([
CondNode(
cond=lambda x: isinstance(x, int),
then=FinalNode("It's an integer!")
),
CondNode(
cond=lambda x: isinstance(x, str),
then=FinalNode("It's a string!")
)
])
# Get first match
result = next(router(42))
assert result == "It's an integer!"
Nested Conditions:
# Nested routing with multiple conditions
router = RoutingForest([
CondNode(
cond=lambda x: isinstance(x, (int, str)),
then=RoutingForest([
CondNode(
cond=lambda x: int(x) >= 10,
then=FinalNode("≥ 10")
),
CondNode(
cond=lambda x: int(x) % 2 == 1,
then=FinalNode("Odd number")
)
])
)
])
# Can get all matches or just first
list(router(15)) # ['≥ 10', 'Odd number']
next(router(8), None) # None (no matches)
Pattern Matching Example:
# Router as pattern matcher
def route_value(value):
router = RoutingForest([
CondNode(
cond=lambda x: x < 0,
then=FinalNode("negative")
),
CondNode(
cond=lambda x: x == 0,
then=FinalNode("zero")
),
CondNode(
cond=lambda x: x > 0,
then=FinalNode("positive")
)
])
return next(router(value), "unknown")
assert route_value(-5) == "negative"
assert route_value(0) == "zero"
assert route_value(10) == "positive"
Key Features:
- Objectify nested if/then logic into composable components
- Both callable and iterable nodes
- Get first match, all matches, or default values
- Cleaner than nested if/elif/else chains for complex routing
- Reusable condition components
i2.util - Utility Functions and Helpers
util provides miscellaneous utility functions for common patterns.
Identity and Constant Functions:
from i2.util import asis, return_true, return_false, return_none
# Identity function
assert asis(42) == 42
assert asis([1, 2, 3]) == [1, 2, 3]
# Constant functions (useful as defaults)
assert return_true("anything", goes="here") is True
assert return_false("doesn't", "matter") is False
assert return_none(1, 2, 3) is None
Object Naming:
from i2.util import name_of_obj
# Get name of various objects
assert name_of_obj(map) == 'map'
assert name_of_obj([1, 2, 3]) == 'list'
assert name_of_obj(lambda x: x) == '<lambda>'
from functools import partial
assert name_of_obj(partial(print, sep=",")) == 'print'
Immutable dict:
from i2.util import imdict
# An immutable dict: reads work, mutations raise TypeError
data = imdict({'a': 1, 'b': 2})
assert data['b'] == 2
try:
data['c'] = 3
raise AssertionError("imdict should not be mutable")
except TypeError:
pass
Laziness Utilities:
from i2.util import lazyprop
class DataLoader:
@lazyprop
def expensive_data(self):
print("Loading...")
return [1, 2, 3, 4, 5]
loader = DataLoader()
# First access computes and caches
data1 = loader.expensive_data # Prints "Loading..."
# Subsequent accesses use cached value
data2 = loader.expensive_data # No print
assert data1 is data2
Key Features:
- Common function patterns (identity, constants)
- Object introspection helpers
- Flexible attribute/item access wrappers
- Lazy evaluation utilities
- Deprecation helpers
- String manipulation tools
Common Patterns
Composing Transformations
from i2.castgraph import TransformationGraph
from i2.wrapper import Wrap
# Define transformation graph
graph = TransformationGraph()
@graph.register_edge('csv', 'rows')
def parse_csv(text, ctx):
return [line.split(',') for line in text.strip().split('\n')]
@graph.register_edge('rows', 'records')
def rows_to_records(rows, ctx):
headers, *data = rows
return [dict(zip(headers, row)) for row in data]
# Use with wrapper for clean API
def process_csv(csv_text: str) -> list:
return graph.transform(csv_text, 'records', from_kind='csv')
# Wrap to add validation
validated = Wrap(
process_csv,
ingress=lambda csv_text: ((csv_text.strip(),), {}),
egress=lambda records: [r for r in records if any(r.values())] # drop empty records
)
assert validated(" name,age\nann,3\n,\n") == [{'name': 'ann', 'age': '3'}]
Dynamic Signature Manipulation
from i2.signatures import Sig
# Start with a general function
def process(**kwargs):
return sum(kwargs.values())
# Give it a specific signature
@Sig('a b c')
def typed_process(**kwargs):
return process(**kwargs)
# Now can call with clear (keyword) parameters
result = typed_process(a=1, b=2, c=3)
assert result == 6
Routing with Validation