如何将原始类型的序列类型为newtypes?

发布于 2025-02-08 20:44:53 字数 633 浏览 1 评论 0原文

假设我的功能返回str s的列表。我想将其分配给从str继承的newtypes列表。

不幸的是,我找不到使用键入模块来完成此操作的方法。我唯一的解决方案是循环浏览列表,将每个元素转换为新列表。通常如何处理?

谢谢。

import pathlib 
from typing import List, NewType

Line = NewType('Line', str)
Lines = NewType('Lines', List[Line])

def read(
    file_name: str,
) -> List[str]:
    file_path = pathlib.Path.cwd() / file_name
    ret = file_path.read_text().splitlines(keepends=True)
    return ret

def main():
    a: Lines
    a = Lines(
        read("a.txt") # type problem: str is incompatible with Line
    )

Say I have a function that returns a list of strs. I want to assign it to a list of NewTypes that inherit from str.

Unfortunately, I can't find a way to do this with the typing module. The only solution I have is looping through the list, convert every single element and append it to a new list. How is this normally handled?

Thank you.

import pathlib 
from typing import List, NewType

Line = NewType('Line', str)
Lines = NewType('Lines', List[Line])

def read(
    file_name: str,
) -> List[str]:
    file_path = pathlib.Path.cwd() / file_name
    ret = file_path.read_text().splitlines(keepends=True)
    return ret

def main():
    a: Lines
    a = Lines(
        read("a.txt") # type problem: str is incompatible with Line
    )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文