Instance-scoped routing engine for Python with hierarchical handlers and composable plugins
Project description
SmartRoute
SmartRoute is a fully runtime routing engine that lets you expose Python methods as "endpoints" (CLI tools, orchestrators, internal services) without global blueprints or shared registries. Each instance creates its own routers, can attach child routers, configure plugins, and provides ready-to-use runtime introspection. It's the successor to SmartSwitch, preserving the core idea of method "switching" but with a simpler design and no compatibility layers.
Use SmartRoute when you need to:
- Compose internal services with many handlers (application APIs, orchestrators, CLI automation)
- Build dashboards/portals that register routers dynamically and need runtime introspection
- Extend handler behavior with plugins (logging, validation, audit trails)
SmartRoute provides a consistent, well-tested foundation for these patterns.
Key Features
- Instance-scoped routers – Each object instantiates its own routers (
Router(self, ...)) with isolated state. - Friendly registration –
@route(...)accepts explicit names, auto-strips prefixes, and supports custom metadata. - Simple hierarchies –
add_child("child1, child2")connects child routers with dotted path access (parent.api.get("child.method")). - Plugin pipeline –
BasePluginprovideson_decore/wrap_handlerhooks and plugins inherit from parents automatically. - Runtime configuration –
routedclass.configure()applies global or per-handler overrides with wildcards and returns reports ("?"). - Optional extras –
logging,pydanticplugins and SmartAsync wrapping are opt-in; the core has minimal dependencies. - Full coverage – The package is 100% covered by Pytest (65 scenarios) with no hidden compatibility layers.
Quick Example
from smartroute import RoutedClass, Router, route
class OrdersAPI(RoutedClass):
def __init__(self, label: str):
self.label = label
self.api = Router(self, name="orders")
@route("orders")
def list(self):
return ["order-1", "order-2"]
@route("orders")
def retrieve(self, ident: str):
return f"{self.label}:{ident}"
@route("orders")
def create(self, payload: dict):
return {"status": "created", **payload}
orders = OrdersAPI("acme")
print(orders.api.get("list")()) # ["order-1", "order-2"]
print(orders.api.get("retrieve")("42")) # acme:42
overview = orders.api.members()
print(overview["handlers"].keys()) # dict_keys(['list', 'retrieve', 'create'])
Installation
pip install smartroute
For development:
git clone https://github.com/genropy/smartroute.git
cd smartroute
pip install -e ".[all]"
To use the Pydantic plugin:
pip install smartroute[pydantic]
Core Concepts
Router– Runtime router bound directly to an object viaRouter(self, name=\"api\")@route(\"name\")– Decorator that marks bound methods for the router with the matching nameRoutedClass– Mixin that tracks routers per instance and exposes theroutedclassproxyBasePlugin– Base class for creating plugins withon_decoreandwrap_handlerhooksobj.routedclass– Proxy exposed by every RoutedClass that provides helpers likeget_router(...)andconfigure(...)for managing routers/plugins without polluting the instance namespace.
Pattern Highlights
- Explicit naming + prefixes –
@route("api", name="detail")andRouter(prefix="handle_")separate method names from public route names (test_prefix_and_name_override). - Attribute-level hierarchies –
self.api.add_child("sales, finance")connects child routers by discovering them from instance attributes (test_dashboard_hierarchy). - Bulk registration – Dictionaries or iterables allow connecting routers from external structures (
test_add_child_accepts_mapping_for_named_children). - Built-in and custom plugins –
Router(...).plug("logging"),Router(...).plug("pydantic")or custom plugins (llm-docs/PATTERNS.md#pattern-12-custom-plugin-development). - Runtime configuration –
routedclass.configure("api:logging/foo", enabled=False)applies targeted overrides with wildcards or batch updates (see dedicated guide). - Dynamic registration –
router.add_entry(handler)orrouter.add_entry("*")allow publishing handlers computed at runtime (tests/test_router_runtime_extras.py).
Documentation
- Full Documentation – Complete guides, tutorials, and API reference
- Quick Start – Get started in 5 minutes
- LLM Reference – Token-optimized reference for AI code generation
- API Details – Complete API reference generated from tests
- Usage Patterns – Common patterns extracted from test suite
Testing
SmartRoute achieves 100% statement coverage with 59 comprehensive tests:
PYTHONPATH=src pytest --cov=src/smartroute --cov-report=term-missing
All examples in documentation are verified by the test suite and linked with test anchors.
Repository Structure
smartroute/
├── src/smartroute/
│ ├── core/ # Core router implementation
│ │ ├── router.py # Router runtime implementation
│ │ ├── decorators.py # @route and @routers decorators
│ │ └── base.py # BasePlugin and MethodEntry
│ └── plugins/ # Built-in plugins
│ ├── logging.py # LoggingPlugin
│ └── pydantic.py # PydanticPlugin
├── tests/ # Test suite (>95% coverage)
│ ├── test_switcher_basic.py # Core functionality
│ ├── test_router_edge_cases.py # Edge cases
│ ├── test_plugins_new.py # Plugin system
│ └── test_pydantic_plugin.py # Pydantic validation
├── docs/ # Human documentation (Sphinx)
├── llm-docs/ # LLM-optimized documentation
└── examples/ # Example implementations
Project Status
SmartRoute is currently in alpha (v0.4.1). The core API is stable with complete documentation.
- Test Coverage: 100% (66 tests, 724 statements)
- Python Support: 3.10, 3.11, 3.12
- License: MIT
Current Limitations
- Instance methods only – Routers assume decorated functions are bound methods (no static/class method or free function support)
- No SmartAsync plugin –
get(..., use_smartasync=True)is optional but there's no dedicated SmartAsync plugin - Minimal plugin system – Intentionally simple; advanced features (e.g., Pydantic declarative config) must be added manually
Roadmap
- ✅ Complete Sphinx documentation with tutorials and API reference
- Additional plugins (async, storage, audit trail, metrics)
- Benchmarks and performance comparison
- Example applications and use cases
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
MIT License - see LICENSE for details.
Acknowledgments
SmartRoute is the successor to SmartSwitch, designed with lessons learned from production use.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file smartroute-0.4.1.tar.gz.
File metadata
- Download URL: smartroute-0.4.1.tar.gz
- Upload date:
- Size: 27.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
816fbad0aae8a51f64ef2926388826619020951fe273de372e18bf7cc48c0203
|
|
| MD5 |
cf2db6064651fef7c8fa97e22f858abf
|
|
| BLAKE2b-256 |
d5aa49964deef8b58f50cbd3a6064c6fb2b8f318be0a82c725a71d476c6beef6
|
Provenance
The following attestation bundles were made for smartroute-0.4.1.tar.gz:
Publisher:
publish.yml on genropy/smartroute
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
smartroute-0.4.1.tar.gz -
Subject digest:
816fbad0aae8a51f64ef2926388826619020951fe273de372e18bf7cc48c0203 - Sigstore transparency entry: 708753749
- Sigstore integration time:
-
Permalink:
genropy/smartroute@262ce0779ab3999bb9c27c2f0ccf7ce7daed2205 -
Branch / Tag:
refs/tags/v0.4.1 - Owner: https://github.com/genropy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@262ce0779ab3999bb9c27c2f0ccf7ce7daed2205 -
Trigger Event:
push
-
Statement type:
File details
Details for the file smartroute-0.4.1-py3-none-any.whl.
File metadata
- Download URL: smartroute-0.4.1-py3-none-any.whl
- Upload date:
- Size: 18.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3418e0ec8d03a2da4e082c4600557b4b1e6cacd1a6740b0698b63d603925bb06
|
|
| MD5 |
080bdad691e782fb3b2c5fbfc45b4023
|
|
| BLAKE2b-256 |
56f3edefbe616a2af5d362eeee2bff6941e4adcb5365277985abc8f22e76bbea
|
Provenance
The following attestation bundles were made for smartroute-0.4.1-py3-none-any.whl:
Publisher:
publish.yml on genropy/smartroute
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
smartroute-0.4.1-py3-none-any.whl -
Subject digest:
3418e0ec8d03a2da4e082c4600557b4b1e6cacd1a6740b0698b63d603925bb06 - Sigstore transparency entry: 708753754
- Sigstore integration time:
-
Permalink:
genropy/smartroute@262ce0779ab3999bb9c27c2f0ccf7ce7daed2205 -
Branch / Tag:
refs/tags/v0.4.1 - Owner: https://github.com/genropy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@262ce0779ab3999bb9c27c2f0ccf7ce7daed2205 -
Trigger Event:
push
-
Statement type: