如何将原始类型的序列类型为newtypes?
假设我的功能返回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 str
s. 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论