跳转到主要内容

Python的Typed resolver(依赖容器)

项目描述

tres

Python的Typed resolver(依赖容器)

它提供了一个依赖容器,供您在类型依赖解析中使用。

就是这样。非常类型解析。非常棒。

tsyringe中的依赖容器启发,但更Python化。

用法

from tres import container, InjectionToken

def a(n: int) -> str:
    return str(n)


def b(a: int, b: int) -> int:
    return a + b


a_token = InjectionToken[Callable[[int], str]]()
b_token = InjectionToken[Callable[[int, int], int]]()

container.register(a_token, a)
container.register(b_token, b)
container.register(b_token, a)  # type error


def c(f: Callable[[int], str]):
    print(f(1))


c(container[a_token])
c(container[b_token])  # type error

注册协议的更长的示例

# application logic

from typing import Protocol, Iterable

class OrdersProtocol(Protocol):
    def byId(self, id) -> Order:
        ...

    def getLines(self, id) -> Iterable[OrderLine]:
        ...

OrdersStoreToken = tres.InjectionToken[OrdersProtocol]()

def calculate_total(orders_store: OrdersProtocol, order_id):
    order = orders_store.byId(order_id)
    lines = orders_store.getLines(order_id)
    return sum(line.price for line in lines) + order.shipping


# implementation

from config import URLfrom domain import Order, OrderLine
from application import OrdersProtocol, OrdersStoreToken

class OrdersStore(OrdersProtocol):
    def __init__(self, url):
        self.url = url

    def byId(self, id):
        return map(Order, requests.get(f'{self.url}/order/{id}').json())

    def getLines(self, id):
        return map(OrderLine, requests.get(f'{self.url}/order/{id}/lines').json())

tres.container.register(OrdersStoreToken, OrdersStore(URL))


# consumer

from application import calculate_total, OrdersStoreToken

def order_view(order_id):
    orders_store = tres.container[OrdersStoreToken]
    order = orders_store.byId(order_id)
    total = calculate_total(orders_store, order_id)
    return f'{order.id} - {order.date}: {total}'

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

tres-1.3.tar.gz (2.9 kB 查看散列)

上传时间:

构建分发

tres-1.3-py2.py3-none-any.whl (4.5 kB 查看散列)

上传时间: Python 2 Python 3

由以下机构支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误记录StatusPageStatusPage状态页面