如何使用pydantic创建链接列表,因此自动完成不突破
我正在尝试使用Pydantic创建一个链接列表。
以下代码有效,但我无法使自动完成工作。从附件的屏幕截图中可以看到,属性“ Next”不会显示自动完成。
我如何保留自动comp
更新:我正在研究Pycharm Professional 2020.3 + Python 3.10.2 + Pydantic 1.9.0
代码
from pydantic import BaseModel
from pydantic.typing import ForwardRef
Node = ForwardRef('Node')
class Node(BaseModel):
data: int
next: Node = None
# Node.update_forward_refs()
def get_l1() -> Node:
l1: Node = Node(data=1)
l1.next = Node(data=2)
l1.next.next = Node(data=3)
return l1
l2: Node = get_l1()
print(l2)
print(l2.next)
print(l2.next.next)
输出
data=1 next=Node(data=2, next=Node(data=3, next=None))
data=2 next=Node(data=3, next=None)
data=3 next=None
屏幕截图
I am trying to create a linked list using pydantic.
The following code works, but I can't get auto-completion to work. As you can see from the attached screenshot, the property 'next' doesn't show auto-completion.
How do I preserve the auto-comp
Update: I am working on Pycharm Professional 2020.3 + Python 3.10.2 + pydantic 1.9.0
Code
from pydantic import BaseModel
from pydantic.typing import ForwardRef
Node = ForwardRef('Node')
class Node(BaseModel):
data: int
next: Node = None
# Node.update_forward_refs()
def get_l1() -> Node:
l1: Node = Node(data=1)
l1.next = Node(data=2)
l1.next.next = Node(data=3)
return l1
l2: Node = get_l1()
print(l2)
print(l2.next)
print(l2.next.next)
Output
data=1 next=Node(data=2, next=Node(data=3, next=None))
data=2 next=Node(data=3, next=None)
data=3 next=None
Screenshot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请勿使用
forwardRef
,使用typing.optional
,因为您将none
分配给 node> node field and collendnode
带引号:关于
键入。 rel =“ nofollow noreferrer”> pydantic文档:
关于引号的用法在类型的提示中,根据:
Do not use
ForwardRef
, usetyping.Optional
because you are assigningNone
to thenode
field and surroundNode
with quotes:About
typing.Optional
from the pydantic documentation:About the usage of quotes in a type hint of a forward reference according to PEP 484: