跳转到主要内容

Strictus Dictus

项目描述

pip install strictus-dictus

StrictusDictus(又名sdict)是特殊dict子类的基类,其实例仅接受在类的类型提示中声明的键。

这对于数据传输对象定义很有用,例如,当您在代码中表示他人的JSON或YAML架构,并希望使用点表示法访问解析字典的内容时,同时希望您的IDE自动完成属性名称。

sdict适用于嵌套结构。

from strictus_dictus import sdict

class Header(sdict):
    title: str = "Hello, world!"  # default value
    sent: str

class Tag(sdict):
    value: str

class Message(sdict):
    header: Header
    body: str
    tags: List[Tag]

source = {
    "header": {
        "sent": "2018-10-20 18:09:42",
    },
    "body": "What is going on?",
    "tags": [
        {
            "value": "unread",
        },
    ],
}

# Parse the message
message = Message(source)

# Access attributes
assert message.header.title == "Hello, world!"
assert message.tags[0].value == "unread"

# It still is a dictionary so this works too:
assert message["header"]["title"] == "Hello, world!"

# Convert back to a standard dictionary
message.to_dict()

这些键的值可以使用点表示法或[]表示法访问,但是,如果源字典缺少键,StrictusDictus不会引入它,因此通过[]表示法访问将引发预期的KeyError。但是,属性将被初始化以保存特殊的EMPTY值。

要创建实例,请使用YourClass(standard_dict),要将导出转换为标准字典,请使用YourClass().to_dict()

StrictusDictus 仅支持有限类型的类型提示。不支持的类型提示将被静默忽略,并且返回的值将不会被处理。

支持的类型提示有(SD 表示从 StrictusDictus 继承的任何类)

class Examples:
    x1: primitive_type  # could be any type, but not from typing.*; value won't be processed
    x2: List  # unprocessed list
    x3: Dict  # unprocessed dictionary
    x4: SD
    x5: List[SD]
    x6: Dict[str, SD]

您可以使用 List[Any]Dict[Any, Any] 来注释 x,但 StrictusDictus 不会处理这些值。

限制

  • sdict 子类不能在其类型提示中引用自身(即使是使用向前引用)。

数据类?

数据类是一个很好的构建块,但它并没有认真对待字典。

@dataclasses.dataclass
class Point:
    x: float
    y: float

@dataclasses.dataclass
class Line:
    start: Point
    end: Point

line = Line(**{"start": {"x": 1, "y": 1}, "end": {"x": 5, "y": 5}})

我原本期望 line.end.y 保存值为 5,但事实并非如此。实际上,print(line.end.y) 会引发一个 AttributeError

AttributeError: 'dict' object has no attribute 'y'

项目详情


下载文件

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

源分布

strictus-dictus-0.0.12.tar.gz (5.2 kB 查看散列)

上传时间

构建分布

strictus_dictus-0.0.12-py3-none-any.whl (5.0 kB 查看散列)

上传时间 Python 3

支持者