移植 Python 项目到 typescript,如何处理 Python attrs 库呢

2021-12-05 10:35:29 +08:00
 AkideLiu

各位彦祖好,最近在把一个 python 写的项目改写成 typescript

发现原始 python 代码里面使用了大量的 attr.ib(),在 attr.ib()里面有很多的参数比如 cmp ,factory ,converter ,validator 等等。

初步想法是用 ts class 的 constructor 来实现类似的功能,但是这样的话上面提到的细节参数都需要有单独的验证和处理,请问有什么适用于 typescript 类似于 attr 的库方便实现这样的功能吗?

attrs 的官方文档 : https://www.attrs.org/en/stable/

看完官方文档和例子感觉有点像 java 的 lombok

一段例子如下:

https://github.com/cs50/compare50/blob/main/compare50/_data.py#L114-L149

@attr.s(slots=True, frozen=True)
class Submission:
    """
    :ivar path: the file path of the submission
    :ivar files: list of :class:`compare50.File` objects contained in the submission
    :ivar preprocessor: A function from tokens to tokens that will be run on \
            each file in the submission
    :ivar id: integer that uniquely identifies this submission \
            (submissions with the same path will always have the same id).
    Represents a single submission. Submissions may either be single files or
    directories containing many files.
    """
    _store = IdStore(key=lambda sub: (sub.path, sub.files, sub.large_files, sub.undecodable_files))

    path = attr.ib(converter=pathlib.Path, cmp=False)
    files = attr.ib(cmp=False)
    large_files = attr.ib(factory=tuple, converter=_to_path_tuple, cmp=False, repr=False)
    undecodable_files = attr.ib(factory=tuple, converter=_to_path_tuple, cmp=False, repr=False)
    preprocessor = attr.ib(default=lambda tokens: tokens, cmp=False, repr=False)
    is_archive = attr.ib(default=False, cmp=False)
    id = attr.ib(init=False)


    def __attrs_post_init__(self):
        object.__setattr__(self, "files", tuple(
            [File(pathlib.Path(path), self) for path in self.files]))
        object.__setattr__(self, "id", Submission._store[self])

    def __iter__(self):
        return iter(self.files)

    @classmethod
    def get(cls, id):
        """Retrieve submission corresponding to specified id"""
        return cls._store.objects[id]
2261 次点击
所在节点    Python
3 条回复
Opportunity
2021-12-05 14:46:50 +08:00
gouflv
2021-12-05 16:39:31 +08:00
class-transformer + class-validator
pengtdyd
2021-12-05 17:09:07 +08:00
改啥改,又不是不能用

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/820121

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX