【发布时间】:2023-04-05 05:59:01
【问题描述】:
当涉及到构造函数、赋值和方法调用时,PyCharm IDE 非常擅长分析我的源代码并确定每个变量应该是什么类型。我喜欢它正确的时候,因为它给了我很好的代码完成和参数信息,如果我尝试访问一个不存在的属性,它会给我警告。
但是当涉及到参数时,它什么都不知道。代码完成下拉菜单不能显示任何内容,因为他们不知道参数将是什么类型。代码分析无法查找警告。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
peasant = Person("Dennis", 37)
# PyCharm knows that the "peasant" variable is of type Person
peasant.dig_filth() # shows warning -- Person doesn't have a dig_filth method
class King:
def repress(self, peasant):
# PyCharm has no idea what type the "peasant" parameter should be
peasant.knock_over() # no warning even though knock_over doesn't exist
King().repress(peasant)
# Even if I call the method once with a Person instance, PyCharm doesn't
# consider that to mean that the "peasant" parameter should always be a Person
这有一定的意义。其他呼叫站点可以为该参数传递任何内容。但是,如果我的方法需要一个参数类型,比如pygame.Surface,我希望能够以某种方式向 PyCharm 表明这一点,这样它就可以在其代码完成中向我显示 Surface 的所有属性下拉菜单,并在我调用错误的方法时突出显示警告,等等。
有没有办法可以给 PyCharm 一个提示,并说“psst,这个参数应该是X 类型”? (或者,本着动态语言的精神,“这个参数应该像 X 一样嘎嘎作响”?我会接受的。)
编辑: CrazyCoder 的回答如下,可以解决问题。对于像我这样想要快速总结的新手,这里是:
class King:
def repress(self, peasant):
"""
Exploit the workers by hanging on to outdated imperialist dogma which
perpetuates the economic and social differences in our society.
@type peasant: Person
@param peasant: Person to repress.
"""
peasant.knock_over() # Shows a warning. And there was much rejoicing.
相关部分是文档字符串的@type peasant: Person 行。
如果您还转到“文件”>“设置”>“Python 集成工具”并将“Docstring 格式”设置为“Epytext”,那么 PyCharm 的“视图”>“快速文档查找”将漂亮地打印参数信息,而不仅仅是将所有 @-lines 打印为-是。
【问题讨论】:
-
需要注意的是,reStructuredText 注释使用相同的标签,只是写法不同:
@param xx: yyy变为:param xx: yyy。见jetbrains.com/pycharm/webhelp/… -
为什么我们可以不指定完全限定的类名?
标签: python pycharm type-hinting python-typing code-completion